Entity Framework 5 Updating a Record

前端 未结 8 1241
悲哀的现实
悲哀的现实 2020-11-22 08:06

I have been exploring different methods of editing/updating a record within Entity Framework 5 in an ASP.NET MVC3 environment, but so far none of them tick all of the boxes

8条回答
  •  心在旅途
    2020-11-22 08:48

    I have added an extra update method onto my repository base class that's similar to the update method generated by Scaffolding. Instead of setting the entire object to "modified", it sets a set of individual properties. (T is a class generic parameter.)

    public void Update(T obj, params Expression>[] propertiesToUpdate)
    {
        Context.Set().Attach(obj);
    
        foreach (var p in propertiesToUpdate)
        {
            Context.Entry(obj).Property(p).IsModified = true;
        }
    }
    

    And then to call, for example:

    public void UpdatePasswordAndEmail(long userId, string password, string email)
    {
        var user = new User {UserId = userId, Password = password, Email = email};
    
        Update(user, u => u.Password, u => u.Email);
    
        Save();
    }
    

    I like one trip to the database. Its probably better to do this with view models, though, in order to avoid repeating sets of properties. I haven't done that yet because I don't know how to avoid bringing the validation messages on my view model validators into my domain project.

提交回复
热议问题