简体   繁体   English

实体框架如何更新子表

[英]Entity Framework How to update child table

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). 我正在使用实体框架工作将数据提取到POCO中(没有问题)。 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. 没有引发异常,新的Car出现在数据库中,但人员行未更改为指向新的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: 这导致一个异常:

A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship. 发生参照完整性约束冲突:定义参照约束的属性值在关系中的主体对象和从属对象之间不一致。

I can't seem to find a simple example to clear things up. 我似乎找不到一个简单的例子来解决问题。

_dbContext.Entry(person).State = EntityState.Modified; _dbContext.Entry(person).State = EntityState.Modified; That tells the entity framework that the whole record has been updated. 这告诉实体框架整个记录已更新。

So you can try this approach: 因此,您可以尝试以下方法:

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

Now entity framework should tracking which columns are being changed. 现在,实体框架应该跟踪要更改的列。

or you can call: 或者您可以致电:

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

it should help too. 它也应该有所帮助。

I think this is very good article about Change Tracking with POCO in EF 我认为这是一篇有关EF中POCO的变更跟踪的很好的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM