Use the following methods to avoid the trouble of assigning values one by one when updating objects. Code:
public static class ReflectionExtensions { public static void CopyPropertiesFrom(this object destObject, object sourceObject) { if (null == destObject) throw new ArgumentNullException("destObject"); if (null == sourceObject) throw new ArgumentNullException("sourceObject"); Type destObjectType = destObject.GetType(); foreach (PropertyInfo sourcePi in sourceObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) { PropertyInfo destPi = destObjectType.GetProperty(sourcePi.Name); if (null != destPi && null != destPi.SetMethod) { object sourcePropertyValue = sourcePi.GetValue(sourceObject); destPi.SetValue(destObject, sourcePropertyValue); } } } }
Call method:
using (DemoDBEntities1 ctx = new DemoDBEntities1()) { var query = (from q in ctx.Cities select q).FirstOrDefault(); City city = new City(); city.Id = query.Id; city.StateID = 101; city.City1 = "test"; query.CopyPropertiesFrom(city); int result = ctx.SaveChanges(); }
Hope to help more people.