简体   繁体   English

实体框架-更新表中的一行

[英]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. 我是Entity Framework的新手,我有一个有关更新表中数据的问题。

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) 假设我要更新“类别”表,并且它只有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();
}

My question is if there are 50 fields in category table I will have to assign each field individually. 我的问题是类别表中是否有50个字段,我将不得不分别分配每个字段。 Can't i do something like this .. catObj = entity; 我不能做这样的事.. catObj =实体; ?

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. 为了解决这个问题,您将必须使用自动映射器配置来正确地进行投影,完全取决于您的需要。

You can change the properties of all members of a collection with a single LINQ operation: 您可以使用单个LINQ操作来更改集合的所有成员的属性:

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

I am not sure that AutoMapper is good for your purpose. 我不确定AutoMapper是否适合您的目的。 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 (eg this.name = entity.name; ) But I do this not by hand but generate them using MVCScaffolding or other code generation techniques. 对于您所描述的,我通常在每个实体中都有一个诸如void CopyEntityFrom(Category Source)的方法,并且在该方法中,我具有映射语句(例如this.name = entity.name; ),但是我不是手工完成而是生成他们使用MVCScaffolding或其他代码生成技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM