1
如何通過使用附加特定對象來更新模型及其子代?實體框架代碼在分離對象上的第一次更新
我使用存儲庫模式,看起來像這樣的舊實體框架:
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
。如何在分離對象的特定屬性上運行更新?