Click here to Skip to main content
14,177,047 members
Click here to Skip to main content
Add your own
alternative version

Stats

15.9K views
2 bookmarked
Posted 24 Oct 2011
Licenced CPOL

Extension Method to help with EF Code First updating

, 24 Oct 2011
Rate this:
Please Sign up or sign in to vote.
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:


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:


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

    _context.SaveChanges();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

George Danila
Software Developer (Junior) IT Perspectives
Romania Romania
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190526.1 | Last Updated 24 Oct 2011
Article Copyright 2011 by George Danila
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid