Daath
Daath

Reputation: 1979

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.

Upvotes: 2

Views: 1511

Answers (3)

mmushtaq
mmushtaq

Reputation: 3520

You can use Entity State for your entity for update as well as for delete and insert..

Update

dbContext.Entry(yourEntity).State = EntityState.Modified;
dbContext.SaveChanges(); 

Insert

dbContext.Entry(yourEntity).State = EntityState.Added;
dbContext.SaveChanges(); 

Delete

dbContext.Entry(yourEntity).State = EntityState.Deleted;
dbContext.SaveChanges(); 

And don't forget to call SaveChanges() at the end of each operation.

For more information, please visit

Entity states and SaveChanges

Upvotes: 1

Daath
Daath

Reputation: 1979

Thanks to all that replied. Here is how I got it to work using the latest version of AutoMapper:

public void UpdateCustomer(Customer customer)
{
    var customerTopdate=dbContext.Customers.Where(c=>c.Id=customer.Id);

    if (customerTopdate != null {
       _mapper.Map(customer,customerTopdate);
       _context.SaveChanges();
    }
}

Upvotes: 0

Tarek Abo ELkheir
Tarek Abo ELkheir

Reputation: 1331

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();
}

Upvotes: 2

Related Questions