使用以下方法可以實現避免Update實體時避免逐一賦值的麻煩。 代碼:
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); } } } }
調用方法:
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(); }
希望能幫助到更多的人。