简体   繁体   中英

Entity Framework updating two tables with one to many relationship

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

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!

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