开发者

Entity framework code first update on detached objects

How do I update a model and its child by using attach with specific objects?

I use repository pattern that looks like this with old entity framework:

    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 sele开发者_运维技巧ctor 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();
    }

But now, code-first does not support db.ObjectStateManager. How can I run an update on specific properties for detached objects?


You can try to use:

context.Entry(user).Property(u => u.Body).IsModified = true;

Where context is your instace of DbContext derived class.


Try

var adapter = (IObjectContextAdapter)context;
adapter.ObjectContext.ObjectStateManager ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜