AnthonyMascia AnthonyMascia - 3 months ago 13
ASP.NET (C#) Question

Using LINQ to update every field in SQL row without specifically declaring each field?

I just wanted to know if there was a way to update every field/property in a SQL row without having to declare an explicit "context.FieldName = model.FieldName" for each field.

What I tried doing was:


  1. Pass in the updated model object to the method.

  2. Get the DTO object from the db context based on the model object's ID

  3. If not null, using AutoMapper, convert the model object in to a DTO object

  4. Now set the original DTO object to the newly mapped DTO object

  5. Update database (This is where it fails)

  6. Save Context



But if I explicitly set every single DTO field = to its corresponding model field, it works (obviously). But due to frequent database changes, and the sheer amount of SQL fields, I would like to avoid manually updating every single field and maintaining it every time the database is changed.

Answer

If you use the newest version of automapper, you can do something like this:

public void UpdateCustomer(Customer customer)
{
    var customerTopdate=dbContext.Customers.Where(c=>c.Id=customer.Id);
    var result=AutoMapper.Map<Customer>(customer,customerTopdate);
    dbContext.SaveChanges();
}
Comments