[英]entity framework update one parent entity updates another parent entity
I'm new to entity framework. 我是实体框架的新手。 I have an SupplyItem entity
我有一个SupplyItem实体
public class SupplyItem
{
public virtual int Id { get; set; }
public virtual BaseProduct Product
{
get { return product; }
set { product = value; }
}
public virtual Boolean IsPublic
{
get { return isPublic; }
set { isPublic = value; }
}
}
When I add an supplyitem object for the first time, it is adding a product and IsPublic attribute correctly. 当我第一次添加一个supplyitem对象时,它正确地添加了product和IsPublic属性。 Like this, I added two objects for supplyitem entity, both objects are referencing to same product.
这样,我为supplyitem实体添加了两个对象,这两个对象都引用相同的产品。
Now, I changed isPublic attribute for second object of supplyitem entity and updates the entity like this 现在,我更改了supplyitem实体的第二个对象的isPublic属性,并像这样更新了该实体
UnitOfWork.Context.Entry(supplyItem1).State = EntityState.Modified;
Above code line, updates isPublic attribute correctly but it makes null Product for another object of supplyitem entity which is referencing to the same product. 在代码行上方,正确地更新了isPublic属性,但对于供稿项实体的另一个引用同一产品的对象,该产品为null。
I don't understand this behavior. 我不了解这种行为。 Any pointer will be really helpful !
任何指针都将真正有帮助! Thanks.
谢谢。
uh,when you update,you're not read from db,you new a SupplyItem and set id,set IsPublic,and save,so the object you new it,Product property is default (null) 呃,当您更新时,您不会从db读取数据,而是新建了SupplyItem并设置了id,设置了IsPublic,然后保存了,所以您新建的对象,产品属性为默认值(null)
when you do these,the whole object (every property) updated. 当您执行这些操作时,整个对象(每个属性)都会更新。 so if you want update parts of fields,you should do like this
因此,如果您要更新部分字段,则应这样做
var entry = db.Entry(entity);
if (entry.State == EntityState.Detached)
{
db.Set<TEntity>().Attach(entity);
}
entry.Property("propertyName").IsModified = true
the propertyName is a string ,it must be same as the property's Name you can do this with a lamda propertyName是一个字符串,它必须与属性的名称相同,您可以使用lamda进行操作
Update<TEntity>(TEntity entity, params Expression<Func<TEntity, object>>[] updateProperty)
so in the function,you need find the propetyname from expression 因此在函数中,您需要从表达式中找到属性名称
public static string GetExpressionText<TModel, TProperty>(Expression<Func<TModel, TProperty>> ex)
{
if (ex.Body.NodeType == ExpressionType.MemberAccess)
{
var memExp = ex.Body as MemberExpression;
if (memExp != null)
{
return memExp.Member.Name;
}
}
else if (ex.Body.NodeType == ExpressionType.Convert)
{
var exp = ex.Body as UnaryExpression;
return GetExpressionText(exp);
}
return string.Empty;
}
public static string GetExpressionText(UnaryExpression exp)
{
if (exp != null)
{
if (exp.Operand.NodeType == ExpressionType.MemberAccess)
{
var memExp = exp.Operand as MemberExpression;
if (memExp != null)
{
return memExp.Member.Name;
}
}
}
return string.Empty;
}
hope these code can help you 希望这些代码可以帮助您
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.