從EF select返回元組

.net c# entity-framework linq-to-entities

如何使用EF4在Select中檢索元組?

        var productCount = (from product in context.products
                    select new Tuple<Product, int>(product, products.Orders.Count));

要么

        var productCount = (from product in context.products
                    select Tuple.Create(product, products.Orders.Count));

實體框架說第一種情況不能使用空構造函數,而第二種情況則不能識別Tuple.Create方法。

一般承認的答案

如何切換到投影的LINQ到對象:

var productCount = from product in context.products
                select new {Product = product, Count = products.Orders.Count };
var final = from item in productCount.AsEnumerable()
            select Tuple.Create(item.Product, item.Count);

熱門答案

嘗試

 var productCount = from product in context.products 
                    select new { product, Count = products.Orders.Count }; 

這將返回一個非常接近元組的匿名類型http://msdn.microsoft.com/en-us/library/bb738512.aspx



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因