2

I want to join 2 tables using linq and avoid anonymous object.

So far i use tuple.

var products = from tm in db.TargetMarkets
                join tp in db.Products on tm.product_id equals tp.id
                where tm.country == 2
                select Tuple.Create<TargetMarket, Product>(tm, tp);

But, when i foreach

foreach (var p in products)
{
    var a = p.Item1.id;
}

It throws an exception

LINQ to Entities does not recognize the method 'System.Tuple`2

Question:

  1. Is there a way to keep my code strongly typed
  2. What's wrong with tuple (optional)
abatishchev
  • 98,240
  • 88
  • 296
  • 433
PJ3
  • 3,870
  • 1
  • 30
  • 34

1 Answers1

4

Is there a way to keep my code strong type

You can define a new type and make object of that type instead of anonymous object.

class ProductTargetMarket
{
   //Attributes
} 

var ProductsTargetMarkets = from tm in db.TargetMarkets
            join tp in db.Products on tm.product_id equals tp.id
            where tm.country == 2
            select new ProductTargetMarket{Attribute1OfProductTargetMarket = tp.Attribute1, Attribute1OfProductTargetMarket = tm.Attribute1 };

To create a tuple you may first convert it to anonymous type and then convert it to tuple, see this this and this post.

Community
  • 1
  • 1
Adil
  • 146,340
  • 25
  • 209
  • 204
  • 1
    Thanks. it works!. i just wondering "linq query" syntax for, first return anonymous type and convert it to tuple. (optional & googled) :) – PJ3 Jan 29 '16 at 06:09