What is the correct way to update many of the many using EF?

I am curious how to correctly update the list of objects at a time.

public ActionWas Update(IEnumerable<surcharge_template> templates) { try { var templatesToBeUpdated = _context.surcharge_template.Where(x => templates.Select(template => template.st_key).Contains(x.st_key)); //Right here I need to map all of the differences from the original templates //to the new templates _context.Entry(templatesToBeUpdated).State = EntityState.Modified; } catch (Exception ex) { return _exceptionConverter.Convert(ex); } _context.SaveChanges(); return ActionWas.Successsful; } 

I put a comment in a place where I'm not sure how to handle this. I get the source templates from the database, and then I need to match them, and then commit and save.

So what is the correct way to match them?

UPDATE:

I would like to do this with EF, only making one call to the database. Enumerating the list will result in multipe update statements.

+5
source share
2 answers

You do not need to display the current object. Instead, you can use syntax like SQL Update.

Use EntityFramework.Extended

 //update all tasks with status of 1 to status of 2 context.Templates.Update( t => t.StatusId == 1, t2 => new Template {StatusId = 2}); 

This is just a workaround, in the end, if you need to make different changes for each template, you will need to change the status of the entity.

+1
source

The Attach method does not attach entities. To do this, you need to link all the goals of the dependents that you want to update. You can use GraphDiff to update the full graph without snapping objects. This is something like this:

 using (var context = new TestDbContext()) { // Update the company and state that the company 'owns' the collection Contacts. context.UpdateGraph(company, map => map .OwnedCollection(p => p.Contacts, with => with .AssociatedCollection(p => p.AdvertisementOptions)) .OwnedCollection(p => p.Addresses) ); context.SaveChanges(); } 

This is a brief introduction to the framework.

Hope this help!

0
source

Source: https://habr.com/ru/post/1208425/


All Articles