17

How can I retrieve Tuples at Select using EF4?

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

Or

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

Entity framework says that cant use not empty constructor for first case, and not recognize Tuple.Create method for second.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Felipe Pessoto
  • 6,855
  • 10
  • 42
  • 73

2 Answers2

21

How about switching to LINQ-to-Objects for the projection:

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);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    That will be the only option: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=520269 – Craig Stuntz Jan 22 '10 at 16:36
  • Not a bag guess, then, considering ;-p I've upvoted the "connect" item. – Marc Gravell Jan 22 '10 at 16:40
  • I doing this. But dont exists a better choice? – Felipe Pessoto Jan 22 '10 at 18:04
  • Isn't there a downside of having thousands of "anonymous" classes inside an assembly? – springy76 Jan 17 '13 at 12:40
  • @springy76 well, there is an issue in that each of those exists in the IL. Some may be reusable (there's some generics voodoo to try to help that), but frankly I'm not sure that is very useful, and I would expect almost all (like 98%+) to be unique. So: does having extra defs in the IL concern you? It doesn't overly concern me. – Marc Gravell Jan 17 '13 at 12:44
  • 6
    Actually, the downside to this is that EF is still querying for all of the data, not just the columns you're using. – Matt Miller Aug 20 '13 at 21:54
  • @MattMiller I don't believe that's true. The query is getting only the columns you need, either you project it into a Tuple or an anonymous class. – Nelson Reis Jul 15 '14 at 12:12
  • 1
    @NelsonReis Good catch. I take back my previous comment (almost a year ago). It is good to be aware, though, that there are two selects here: the first select is what EF sees, and the second select is performed on in-memory objects after the SQL query is performed (AsEnumerable() triggers query execution, just like ToList()). You should make sure that the first selects only the data that the second uses, as Marc has done here, or the query will wastefully get too much data. – Matt Miller Jul 16 '14 at 14:18
0

Try

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

This will return an anonymous type which is very close to a tuple http://msdn.microsoft.com/en-us/library/bb738512.aspx

Aaron Stainback
  • 3,489
  • 2
  • 31
  • 32