Friday, June 30, 2017

Post Updated values only, using Entity Framework C#

Scenario:
What if One wants to update the values from new model to an existing Entity.

E.g. We have User Entity as follows:

Public class User
{
 public long Id { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
}

/*************** OLD APPROACH *********************/

Update(user updatedUser)
{
var model = context.Users.Where(u => u.Id == Id).FirstOrDefault();
if(model !=null)
{
model.FirstName =updatedUser.FirstName;
model.LastName =updatedUser.LastName;

context.Users.Update(model);
await context.SaveChangesAsync();
}
}



/*************** BETTER APPROACH *********************/


//Generic Method
/// <summary>
        /// This function actually updates the properties of 'target' object based on the values in the 'Source' Object, with the condition: Both Objects must have same type
        /// </summary>
        /// <typeparam name="T">The Generic Entity</typeparam>
        /// <param name="source">The current Object having new Values</param>
        /// <param name="target">The current Object to which new values are to be updated</param>
        public static void CopyValues<T>(T source, T target)
        {
            Type t = typeof(T);

            var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);

            foreach (var prop in properties)
            {
                var value = prop.GetValue(source, null);
                if (value != null)
                    prop.SetValue(target, value, null);
            }
        }

//Update Method

Update(user updatedUser)
{
var model = context.Users.Where(u => u.Id == Id).FirstOrDefault();
if(model !=null)
{
model.FirstName =updatedUser.FirstName;
model.LastName =updatedUser.LastName;

CopyValues(updatedUser,model);

context.Users.Update(model);
await context.SaveChangesAsync();
}
}


Happy Coding!!













No comments:

Post a Comment