实体框架 - 更新表中的行
我是实体框架新手,我有一个关于更新表中数据的问题。
目前,我正在使用以下方法来更新数据,并寻找更好的方法(如果有人可以帮助我)。
假设我正在更新“类别”表,它只有 3 个字段(id、名称、存档)。
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 =实体; ?
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; ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要自动执行此操作,您可以使用诸如 AutoMapper 之类的项目。
但是,您必须小心这一点,因为如果属性没有传入类别的值,它将用非值覆盖旧类别的属性,即使它不是有意的。为了解决这个问题,您必须使用自动映射器配置来正确地进行投影,完全按照您的意愿。
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.
您可以使用单个 LINQ 操作更改集合所有成员的属性:
因此:
You can change the properties of all members of a collection with a single LINQ operation:
So:
我不确定 AutoMapper 是否适合您的目的。此外,您可能还必须指定映射。
对于您所描述的,我通常在每个实体中都有一个诸如
void CopyEntityFrom(Category Source)
的方法,并且在该方法中,我有映射语句(例如this.name =entity.name;
)但我不是手动执行此操作,而是使用 MVCScaffolding 或其他代码生成技术生成它们。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.