简体   繁体   中英

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). 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:

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; 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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