4

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

Community
  • 1
  • 1
JsonStatham
  • 9,770
  • 27
  • 100
  • 181
  • Could you loop them? so attach each one? - But you might, depending on your code, have SiteSplits that are new so will need to be added rather than attached? – David McLean Feb 04 '16 at 11:18
  • 1
    does GetElectricityState include the ElectricityStates? if so, they are in context upon retrieval, and don't have to be attached again (unless they left the ChangeTracker, in which case they have to be retrieved again). – DevilSuichiro Feb 04 '16 at 11:32
  • Yes there might be more or less splits, the existing ones may have been changed too. – JsonStatham Feb 04 '16 at 12:38

1 Answers1

4

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!

Community
  • 1
  • 1
Fabio
  • 11,892
  • 1
  • 25
  • 41