Reputation: 10374
I'm using EF code first to control my data. I have two models, ElectricitySite
and ElectricitySiteSplit
.
ElectricitySite
contains List<ElectricitySiteSplits> ElectricitySiteSplits
, this is a one to many relationship.
I'm trying to write my Update method for the repository layer which will deal with both the tables, so far I have:
public void UpdateElectricitySite(ElectricitySite updatedElectricitySite)
{
var dbElectricitySite = GetElectricitySite(updatedElectricitySite.ElectricitySiteId);
_context.ElectricitySites.Attach(updatedElectricitySite);
_context.Entry(updatedElectricitySite).State = EntityState.Modified;
_context.SaveChanges();
}
I get the following error when I click the Save button:
Attaching an entity of type 'MySolution.Repo.ElectricityModels.ElectricitySiteSplit' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
I think this is because I've not attached my ElectricitySiteSplit
entity however if I add this in below my ElectricitySites attachment:
_context.ElectricitySiteSplits.Attach(updatedElectricitySite.SiteSplits);
I get this error:
Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.List' to 'UtilityBilling.Repo.ElectricityModels.ElectricitySiteSplit'
How do I handle the ElectricitySiteSplits
table update which is contained in updatedElectrcitiySite.SiteSplits
as a list.
FYI - I've already looked here:
Entity Framework 5 Updating a Record
https://msdn.microsoft.com/en-gb/data/jj592676.aspx
Upvotes: 4
Views: 19565
Reputation: 11990
EF does not handle both tables automatically. I have to specify which item was added/updated/removed. Take a look at this thread Cleanly updating a hierarchy in Entity Framework
Hope this helps!
Upvotes: 4