Exclude Property on Update in Entity Framework

后端 未结 5 1138
野性不改
野性不改 2020-11-28 04:53

I\'ve been looking for a proper way to mark a property to NOT be changed when updating a model in MVC.

For example, let\'s take this small model:

cla         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 05:17

    Create new model that will have limited set of properties that you want to update.

    I.e. if your entity model is:

    public class User
    {
        public int Id {get;set;}
        public string Name {get;set;}
        public bool Enabled {get;set;}
    }
    

    You can create custom view model that will allow user to change Name, but not Enabled flag:

    public class UserProfileModel
    {
       public int Id {get;set;}
       public string Name {get;set;}
    }
    

    When you want to do database update, you do the following:

    YourUpdateMethod(UserProfileModel model)
    {
        using(YourContext ctx = new YourContext())
        { 
            User user = new User { Id = model.Id } ;   /// stub model, only has Id
            ctx.Users.Attach(user); /// track your stub model
            ctx.Entry(user).CurrentValues.SetValues(model); /// reflection
            ctx.SaveChanges();
        }
    }
    

    When you call this method, you will update the Name, but Enabled property will remain unchanged. I used simple models, but I think you'll get the picture how to use it.

提交回复
热议问题