0

I inherited some database tables and Entity Framework where I have the following tables:

Table Person
Id (Primary Key)
Sex
CarId (Foreign Key)

Table Car
Id (Primary Key)
Color
ManufacturerId (Foreign Key)

Table Manufacturer
Id (Primary Key)
Name

I'm using Entity Frame work to pull the data into POCOs (without problems). Now, I would like to make a change to one person's car and save back to the DB. I'm having a heck of a time doing this. I have:

Car car= new Car { Color = "gray", Manufacturer = manufacturer};
_dbContext.Cars.Add(car);
_dbContext.SaveChanges();
person.Car = car;
_dbContext.Entry(person).State = EntityState.Modified;
_dbContext.SaveChanges();

No exceptions are thrown, and the new Car appears in the database, but the person row is not changed to point to the new car. Can someone tell me what is going on and how I should be updating? I'm new to Entity Framework.

Incidentally, I've tried other combinations, such as trying

person.CarId = car.Id.

This leads to an exception:

发生参照完整性约束冲突:定义参照约束的属性值在关系中的主体对象和从属对象之间不一致。

我似乎找不到一个简单的例子来解决问题。

4

1 回答 1

1

_dbContext.Entry(person).State = EntityState.Modified; 这告诉实体框架整个记录已更新。

所以你可以试试这个方法:

Car car= new Car { Color = "gray", Manufacturer = manufacturer};
_dbContext.Cars.Add(car);
_dbContext.Person.Attach(person);
person.Car = car;
_dbContext.SaveChanges();

现在实体框架应该跟踪正在更改的列。

或者您可以致电:

_dbContext.DetectChanges();
_dbContext.SaveChanges();

它也应该有帮助。

我认为这是一篇关于在 EF 中使用 POCO 进行变更跟踪的非常好的文章

于 2013-10-09T18:06:43.673 回答