Update實體時如何避免逐一賦值

使用以下方法可以實現避免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();
            }


希望能幫助到更多的人。

發佈了104 篇原創文章 · 獲贊 19 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章