Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to update Many To Many with EF?

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.

like image 993
Robert Avatar asked Nov 10 '22 22:11

Robert


1 Answers

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.

like image 143
Miguel Avatar answered Jan 04 '23 02:01

Miguel