Reputation: 1979
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:
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
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
Upvotes: 1
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
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