When I create a new EF object, I first attach it to the DbSet then set one of its Navigation Properties to a new instance of a different EF object. I then add the first EF to the DbSet and call save. I get the following exception:
System.InvalidOperationException: The changes to the database were committed
successfully, but an error occurred while updating the object context. The
ObjectContext might be in an inconsistent state. Inner exception message: A
referential integrity constraint violation occurred: The property value(s) of
'Location.Id' on one end of a relationship do not match the property value(s)
of 'Pool.LocationId' on the other end.
Here's my code:
ORMContext context = new ORMContext();
var l = context.Locations.Create();
context.Locations.Attach(l);
...set properties
context.Locations.Add(l);
var p = context.Pools.Create();
context.Pools.Attach(p);
p.Location = l;
...set properties
context.Pools.Add(p);
context.SaveChanges();
What I think is happening is the Location
object is new and its Id
is 0
by default. EF is updating the foreign key on Pool
(which is set to 0
) and then Location.Id
gets updated after the Location
object is saved to the database. So Location.Id
is now set to the associated value in the database, say 149
, and Pool.LocationId
is still set to 0
.
How do I avoid this exception? Or how am I suppose to handle it?
You can save after adding the location, that way the reference to the entity will be set
ORMContext context = new ORMContext();
var l = context.Locations.Create();
context.Locations.Attach(l);
...set properties
context.Locations.Add(l);
context.SaveChanges(); // save here, that way the location will get its Id
var p = context.Pools.Create();
context.Pools.Attach(p);
p.Location = l;
...set properties
context.Pools.Add(p);
context.SaveChanges();
That would be a way
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.