我有一個簡單的數據庫,使用EF數據模型來處理。如何使用從方法返回的匿名類型
我的表是這樣的:
客戶表
- 客戶編號
- 客戶名稱
Orders表
- 的OrderId
- 客戶ID FK
- 訂購日期
我使用一個輔助類來查詢我的模型,並在這個類中,我有以下查詢:
public static List<object> GetCustomerOrdersCount()
{
using (OrdersDbEntities context = new OrdersDbEntities())
{
return context.Customers.Select(
c => new
{
CustId = c.CustomerId,
CustName = c.CustomerName,
OrdersCount = c.Orders.Count
}).ToList<object>();
}
}
的唯一回報I型可以用這種方法使用是List<object>
最後我的問題是:如何做我使用從這個查詢中收到的數據?
我可以讀出的值的唯一方法是通過反射:
List<object> custs = Dal.GetCustomerOrdersCount();
foreach (var customer in custs)
{
var properties = customer.GetType().GetProperties();
foreach (var data in properties)
{
var value = data.GetValue(custs[0], null);
}
}
我不知道是否有更好的方法來做到這一點。
爲什麼您使用的對象,而不是客戶?我假設context.Customers是客戶的DbSet? – Maess 2012-04-18 19:31:32
這是我在嘗試返回列表時得到的錯誤:System.Linq。IQueryable '不包含'ToList'的定義和最好的擴展方法重載'System.Linq.ParallelEnumerable.ToList (System.Linq.ParallelQuery )'有一些無效參數 –
Yoav
2012-04-18 19:34:58
請發佈代碼OrdersDbEntities – Maess 2012-04-18 19:36:37