实体框架 - 更新表中的行 [英] Entity Framework - Update a row in a table
问题描述
我是新来的实体框架和我有一个关于表中的更新数据的问题。
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.
比方说,我更新目录表,它只有3个字段(ID,姓名,存档)
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();
}
我的问题是,如果有分类表中50场,我必须每场单独分配。我不能做这样的事.. catObj =实体; ?
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; ?
推荐答案
要自动执行此操作,你也许可以使用项目如的 AutoMapper 。
To do this automatically you could probably use a project such as AutoMapper.
但是你必须要小心,因为如果一个属性不具有的类别传递一个值,它会覆盖旧类别的属性与非价值,即使它并不打算。为了解决这个问题,你将不得不使用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.
这篇关于实体框架 - 更新表中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!