Why won't Entity Framework Core save a new record to an SQLite table having a foreign key?

陌路散爱 提交于 2019-12-12 01:48:28

问题


I have created a following simple SQLite database for experimenting purposes:

CREATE TABLE "cities" 
(
    `id`    INTEGER PRIMARY KEY AUTOINCREMENT,
    `name`  TEXT UNIQUE
);    

CREATE TABLE `people` 
(
    `id`    INTEGER PRIMARY KEY AUTOINCREMENT,
    `city`  INTEGER,
    `name`  TEXT,
    `surname`   TEXT,
    FOREIGN KEY(`city`) REFERENCES `cities`(`id`)
);

Then I have used the SQLite Toolbox by @erikej to generate the model code.

Right after that the following code works just fine:

var context = new SqliteEfcExampleContext();
var city = new Cities {Name = "Praha"};
context.Cities.Add(city);
context.SaveChanges();

This adds the city to the database immediately and this can be seen by an external client.

The following code, however, does nothing:

var context = new SqliteEfcExampleContext();
var city = context.Cities.Single(c => c.Name == "Praha"); // I know this is unsafe
var person = new People {Name = "Jan"};
city.People.Add(person);
context.People.Add(person);
context.SaveChanges();

Even simpler:

var context = new SqliteEfcExampleContext();
var person = new People { Name = "Jan" };
context.People.Add(person);
context.SaveChanges();

works neither. It seems that the mere existence of the foreign key column (even when it is nullable and is not used) makes it impossible to insert a record into the table.

Adding

context.Entry(person).State = EntityState.Added
context.Update(person)

and

context.Dispose()

don't help.

Please tell me what I am doing wrong.

UPDATE:

As soon as I have removed the properties used for the City and People entities to reference each other (to let them work as simple independent tables, the foreign key column is nullable anyway) adding cities has stopped working too.

Also, If I just add a city using context.Cities.Add(city); (calling context.SaveChanges(); after that, but this does not seem to do anything at all in side effects) and try to get it by name later using the same context - it won't find it. I have also tried using context.Local instead of just context.

At the same time, context.Database.ExecuteSqlCommand works just fine and lets me insert a record manually.

来源:https://stackoverflow.com/questions/42547046/why-wont-entity-framework-core-save-a-new-record-to-an-sqlite-table-having-a-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!