Entity Framework 5 Updating a Record

前端 未结 8 1297
悲哀的现实
悲哀的现实 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 09:06

    There are some really good answers given already, but I wanted to throw in my two cents. Here is a very simple way to convert a view object into a entity. The simple idea is that only the properties that exist in the view model get written to the entity. This is similar to @Anik Islam Abhi's answer, but has null propagation.

    public static T MapVMUpdate(object updatedVM, T original)
    {
        PropertyInfo[] originalProps = original.GetType().GetProperties();
        PropertyInfo[] vmProps = updatedVM.GetType().GetProperties();
        foreach (PropertyInfo prop in vmProps)
        {
            PropertyInfo projectProp = originalProps.FirstOrDefault(x => x.Name == prop.Name);
            if (projectProp != null)
            {
                projectProp.SetValue(original, prop.GetValue(updatedVM));
            }
        }
        return original;
    }
    

    Pros

    • Views don't need to have all the properties of the entity.
    • You never have to update code when you add remove a property to a view.
    • Completely generic

    Cons

    • 2 hits on the database, one to load the original entity, and one to save it.

    To me the simplicity and low maintenance requirements of this approach outweigh the added database call.

提交回复
热议问题