如何使用附加特定对象来更新模型及其子项?
我使用旧实体框架看起来像这样的存储库模式:
public User UpdateUser(User user, IEnumerable<System.Linq.Expressions.Expression<Func<User, object>>> properties)
{
if (user.UserId == 0)
{
db.Users.Attach(user);
}
else
{
db.Users.Attach(user);
ObjectStateEntry entry = db.ObjectStateManager.GetObjectStateEntry(user);
foreach (var selector in properties)
{
string propertyName = PropertyToString(selector.Body);
entry.SetModifiedProperty(propertyName);
}
}
context.SaveChanges();
return user;
}
private static string PropertyToString(Expression selector)
{
switch (selector.NodeType)
{
case ExpressionType.MemberAccess:
return ((selector as MemberExpression).Member as PropertyInfo).Name;
break;
case ExpressionType.Convert:
//Needed to recognize bool datatype
return (((selector as UnaryExpression).Operand as MemberExpression).Member as PropertyInfo).Name;
break;
}
throw new InvalidOperationException();
}
但是现在,代码优先不支持db.ObjectStateManager
。如何在分离对象的特定属性上运行更新?
答案 0 :(得分:1)
您可以尝试使用:
context.Entry(user).Property(u => u.Body).IsModified = true;
上下文是DbContext
派生类的实例。
答案 1 :(得分:0)
尝试
var adapter = (IObjectContextAdapter)context;
adapter.ObjectContext.ObjectStateManager ...