5-14 EF使用存儲過程以及LIST泛型對象轉換爲Datatable

今天使用EF根據數據庫生成模型後,發現之前編寫的存儲過程並沒有返回一個實體類,研究後發現寫成了

ALTER proc [dbo].[usp_tree]
@id varchar(max)
AS
declare @str nvarchar(1000);
set @str='with my1 as (select FId,Parent,Name,Code as TagName,leaf from FactoryTree where Parent=('''+@id+''')  union all select FactoryTree.FId,FactoryTree.Parent,FactoryTree.Name,FactoryTree.Code as TagName,FactoryTree.leaf from my1,FactoryTree where my1.FId=FactoryTree.Parent and my1.leaf=0  and FactoryTree.leaf=0)  select * from my1'
print @str
exec (@str)

 

這樣的寫法在EF中默認返回INT類型,而我需要獲取多表查詢的結果返回一個新的實體類,對其進行操作,所以有新寫了一個存儲過程

SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER proc [dbo].[EF_Tree] @id varchar(max) AS BEGIN

with my1 as (select FId,Parent,Name,Code as TagName,leaf from FactoryTree where Parent=(''+@id+'')  union all select FactoryTree.FId,FactoryTree.Parent,FactoryTree.Name,FactoryTree.Code as TagName,FactoryTree.leaf from my1,FactoryTree where my1.FId=FactoryTree.Parent and my1.leaf=0  and FactoryTree.leaf=0)  select * from my1

END

只是去掉了@str就能返回一個實體類,之前使用ADO.NET並沒有這種情況。

 

話說EF還真是好用,改了數據庫只要更新下模型就可以了,很HAPPY。

EF調用存儲過程

var Result = (from p in db.EF_Tree(Fid)
                         select p).ToList();

因爲Result是實體類,而在項目中要用到DataTable轉化JSON(沒辦法,公司項目裏都是用的ADO.NET,我也懶得造輪子)

下一步,就是將Result轉換爲DataTable

 /// <summary>         

/// 將集合類轉換成DataTable         

/// </summary>         

/// <param name="list">集合</param>         

/// <returns></returns>         

public static DataTable MyListToDataTable(IList list)        

{            

DataTable result = new DataTable();            

if (list.Count > 0)            

{               

  PropertyInfo[] propertys = list[0].GetType().GetProperties();                

foreach (PropertyInfo pi in propertys)      

           {              

       result.Columns.Add(pi.Name);       

          }

                for (int i = 0; i < list.Count; i++)      

           {                   

  ArrayList tempList = new ArrayList();           

          foreach (PropertyInfo pi in propertys)       

              {                      

   object obj = pi.GetValue(list[i], null);    

                     tempList.Add(obj);               

      }                  

   object[] array = tempList.ToArray();        

             result.LoadDataRow(array, true);           

      }       

      }          

   return result;        

}

不知道爲什麼網上的例子裏還要在result.Columns.Add(pi.Name,pi.propertyType);      

就一直報錯DataSet不支持System.nullable<>

後來研究了一下刪了pi.propertyType就OK了。

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章