与实体框架添加和更新实体 [英] Adding and updating entities with Entity Framework
问题描述
在我的最后一个项目,我已经使用实体框架5码第一。我完成了我的项目,但必须在开发过程中有很多的痛苦。
In my last project I have used Entity Framework 5 Code First. I completed my project but had a lot of pain during the development process.
我试图解释我下面痛:
我在这样的产品,产品分类,订单,公司,制造商等我的数据访问逻辑层有几个数据类......每个类都有一些其他类的参考。例如,一个产品实例具有产品分类属性。
I had several data classes in my data access logic layer like Product, ProductCategory, Order, Company, Manufacturer etc... Each class has some references to some other classes. For example, a Product instance has a ProductCategory property.
里面添加和我的数据访问对象类的更新方法,我设置的每个属性(除原始类型除外)的状态,以不变或修改的内容。下面是一些DAO类的更新方法的某些部分:
Inside Add and Update methods of my Data Access Object classes I set the states of each property (other than the primitive types) to Unchanged or Modified in the context. Below is some part of an update method of some dao class:
context.Entry(entity).State = System.Data.EntityState.Modified;
if (entity.Category != null)
context.Entry(entity.Category).State = System.Data.EntityState.Unchanged;
if (entity.Manufacturer != null)
context.Entry(entity.Manufacturer).State = System.Data.EntityState.Unchanged;
foreach (var specificationDefinition in entity.SpecificationDefinitions)
{
context.Entry(specificationDefinition).State = System.Data.EntityState.Unchanged;
foreach (var specificationValue in specificationDefinition.Values)
{
context.Entry(specificationValue).State = System.Data.EntityState.Unchanged;
}
}
此代码是这样的。我的一些添加或更新的方法是约30行代码。我想我做错了什么,添加或更新一个实体不应该这么多的痛苦,但是当我不设置对象的状态我要么得到的异常或在数据库中重复的条目。 ?难道我真的必须设置映射到数据库中每个属性的状态
This code goes like this. Some of my add or update methods are about 30 lines of code. I think I am doing something wrong, adding or updating an entity should not be this much pain but when I don't set the states of the objects I either get exception or duplicate entries in the database. Do I really have to set the state of each property that maps to database?
推荐答案
您可以通过替换您的代码:
You can replace your code by:
context.Products.Attach(entity);
context.Entry(entity).State = System.Data.EntityState.Modified;
之所以这样,是一样的(除非相关的实体是在另一个国家已经连接到上下文比不变
之前)是连接
使实体
包括的所有相关对象图中的实体进入状态的情况下不变
。状态设置为修改
之后的实体
只能从改变产品的单独的状态(而不是相关实体)不变
到修改
。
The reason why this is the same (unless the related entities were already attached to the context in another state than Unchanged
before) is that Attach
puts entity
including all related entities in the object graph into the context in state Unchanged
. Setting the state to Modified
afterwards for entity
only changes the state of the product alone (not the related entities) from Unchanged
to Modified
.
这篇关于与实体框架添加和更新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!