1. 程式人生 > 實用技巧 >linq select 實體額外賦值成實體(未測試效率)

linq select 實體額外賦值成實體(未測試效率)

方法:

        /// <summary>
        /// 實體類複製
        /// </summary>
        /// <param name="objold"></param>
        public static dynamic EntityCopy(object objone, object objtow)
        {
            dynamic objnew = new System.Dynamic.ExpandoObject();
            Type myType = objone.GetType();
            Type myType2 
= objtow.GetType(); PropertyInfo currobj = null; PropertyInfo[] myProperties = myType.GetProperties(); for (int i = 0; i < myProperties.Length; i++) { currobj = objone.GetType().GetProperties()[i]; var ss = currobj.GetValue(objone, null
); //currobj.SetValue(objnew, currobj.GetValue(objold, null), null); (objnew as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(new KeyValuePair<string, object>(currobj.Name, ss)); } myProperties
= myType2.GetProperties(); for (int i = 0; i < myProperties.Length; i++) { currobj = objtow.GetType().GetProperties()[i]; var ss = currobj.GetValue(objtow, null); //currobj.SetValue(objnew, currobj.GetValue(objold, null), null); (objnew as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(new KeyValuePair<string, object>(currobj.Name, ss)); } return objnew; }

使用:

//資料集關聯
                var data = (from l in lists
                            join u in UnitWork.Find<Base_User>(null) on l.Creater equals u.Id into userrooms
                            from u in userrooms.DefaultIfEmpty()
                            join h in UnitWork.Find<Hotel>(null) on l.H_Id equals h.Id into hotel
                            from h in hotel.DefaultIfEmpty()
                            join t in UnitWork.Find<Base_MessageType>(null) on l.BM_Id equals t.Id into msgtype
                            from t in msgtype.DefaultIfEmpty()
                            select ObjectHelper.EntityCopy(l, new
                            {
                                BM_Name = t == null ? null : t.Name,
                                H_Name = h == null ? null : h.Name,
                                CreaterName = u == null ? null : u.Name
                            })
                            ).ToList();

結果:

[
    {
      "Contents": "1",
      "BM_Id": 1,
      "SourceId": 1,
      "ReceiveId": 1,
      "H_Id": 3,
      "Status": 1,
      "Creater": 1,
      "CreateTime": "2020-11-03T00:00:00",
      "Id": 3,
      "BM_Name": null,
      "H_Name": "測試酒店",
      "CreaterName": "管理"
    }
}