问题
This question is related to: Saving an explicit entity through Entity Framework
Basically, Jcl's approached worked me. But there's another issue when trying to save the changes, because it tries to insert a duplicate entity which I have set as a foriegn key.
I'm reading location objects from an Excel file, and construct location objects. I need to set the TimeZone property of the location. There's a timezone table, and the timezoneid is set as the foreign key in the location table.
TimeZone tz = LocationsRepo.GetTimeZoneByName(timezone);
if (tz != null)
{
currentLocation.TimeZone = tz;
}
Now when I try to save the location as follows:
// Check if an entirely new entity is added or an existing entity is being updated.
Location existingLocation = locations.SingleOrDefault(
l =>
l.LocationCode.Equals(location.LocationCode, StringComparison.OrdinalIgnoreCase));
if (existingLocation != null)
{
location.LocationId = existingLocation.LocationId;
ClientContext.Entry(existingLocation).State =
ClientContext.Entry(existingLocation).State == System.Data.Entity.EntityState.Added
? System.Data.Entity.EntityState.Detached
: System.Data.Entity.EntityState.Deleted;
}
ClientContext.Entry(location).State = System.Data.Entity.EntityState.Added;
return ClientContext.SaveChanges();
I get the error that I'm trying to insert a duplicate key in the timezone table. I understand this is because the ClientContext doesn't recognize the location.Timezone because it was set outside the ClientContext. So I tried attaching it:
ClientContext.TimeZones.Attach(location.TimeZone);
ClientContext.SaveChanges();
Then I get the error that I'm trying to insert a duplication location object. Because this timezone is already set to a location existing in the database, and it's trying to attach that.
What's the workaround for this?
来源:https://stackoverflow.com/questions/37202341/ef-associated-entity-is-trying-to-add-to-the-database-when-adding-an-entity