Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Extension Method to help with EF Code First updating

0.00/5 (No votes)
24 Oct 2011 2  
An Extension Method that might help you copy over the values from one object to another, provided they are of the same type.

I just started working with EF Code First and MVC 3 and I ran into a bit of trouble when updating the database with a modified entity because the entity I was receiving from the actions parameter was not the same reference as the one in the DbSet.


Here is a small extension method that might help you copy over the values from one object to another, provided they are of the same type:


C#
public static void CopyPropertiesTo<T>(this T source, T destination) where T : class
{
    if(source == null)
    {
        throw new ArgumentNullException("source");
    }

    if (destination == null)
    {
        throw new ArgumentNullException("destination");
    }

    var fields = GetPropertyValues(source);
    // Get property values.
    var properties = FormatterServices.GetObjectData(source, fields);
    FormatterServices.PopulateObjectMembers(destination, fields, properties);
}

private static MemberInfo[] GetPropertyValues<T>(T source) where T : class
{
    var fieldList = new List<MemberInfo>();
    var instanceType = source.GetType();
    while (instanceType != null && instanceType != typeof (Object))
    {
        fieldList.AddRange(instanceType.GetFields(BindingFlags.Public | 
                                                  BindingFlags.NonPublic | 
                                                  BindingFlags.Instance | 
                                                  BindingFlags.DeclaredOnly));
        instanceType = instanceType.BaseType;
    }

    return fieldList.ToArray();
}

You can then use it as follows:


C#
public ActionResult Edit(Entity entity)
{
    var entityInDbSet = _context.Set.SingleOrDefault(x => x.Id == entity.Id);
    entity.CopyPropertiesTo(entityInDbSet);

    _context.SaveChanges();
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here