Reputation: 424
I am new to Entity Framework and i have a question regarding updating data in a table.
Currently, I am using the following approach to update data and looking for a better way if somebody can help me out.
Let's say I am updating "Category" table and it has only 3 fields(id, name, archived)
private void UpdateCategory(category entity)
{
category catObj = context.category.find(e=> e.id == id);
catObj.name = entity.name;
catObj.archived = entity.archived;
context.savechanges();
}
My question is if there are 50 fields in category table I will have to assign each field individually. Can't i do something like this .. catObj = entity; ?
Upvotes: 2
Views: 11515
Reputation: 20620
I am not sure that AutoMapper is good for your purpose. Also you may have to specify mappings anyway.
For what you described, I usually have a method such as void CopyEntityFrom(Category Source)
in each entity and in the method, I have mapping statements (e.g. this.name = entity.name;
) But I do this not by hand but generate them using MVCScaffolding or other code generation techniques.
Upvotes: 0
Reputation: 27813
To do this automatically you could probably use a project such as AutoMapper.
However you have to be careful with this, because if a property doesn't have a value for the category being passed in, it will overwrite the old category's property with the non-value, even if it's not intended. To get around this you will have to use automapper configurations to do the projection correctly, exactly as you want.
Upvotes: 1
Reputation: 34820
You can change the properties of all members of a collection with a single LINQ operation:
collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();
So:
private void UpdateCategory(category entity)
{
category catObj = context.category.find(e=> e.id == id);
catObj.Select(c=> {c.name = entity.name; c.archived = entity.archived; return c;}).ToList();
context.savechanges();
}
Upvotes: 0