5

I am curious as to what the proper way to update a list of entities at one time is.

    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 at the point where I am not sure the way to handle this. I get the original templates from the database and then I need to map them, then commit and save.

So what is the proper way to map them?

UPDATE:

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

Robert
  • 4,306
  • 11
  • 45
  • 95
  • Repeated question. [Link here](http://stackoverflow.com/questions/10314552/how-to-update-the-multiple-rows-at-a-time-using-linq-to-sql) – Sarbanjeet Dec 10 '14 at 08:01
  • 1
    @Sarbanjeet I did not see anything in that post that talks about how to prevent EF from making multiple update calls to the DB when saveChanges is called. – Robert Dec 10 '14 at 14:10
  • EntityFramework.Extended will help – Miguel Dec 12 '14 at 04:50
  • @Miguel as with Marc's answer below. I do not see where EFExtended can map the original type into the new type in one call. – Robert Dec 15 '14 at 16:15
  • @Robert look the new answer, I was unable to paste formatted code here :-( – Miguel Dec 15 '14 at 21:30

2 Answers2

1

You don't need to map the current entity. You can use a syntax like the SQL Update instead.

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 only a workaround, at the end if you need to do different changes for each Template you will need to modify the entity status.

Miguel
  • 3,786
  • 2
  • 19
  • 32
0

The Attach method don't attach sub-entities. In order to do this, you need to Attach all the dependents target that you want to update. You can use GraphDiff to update a full graph without attaching the entities. The usage 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!

Miguel
  • 3,786
  • 2
  • 19
  • 32