Search code examples
c#entity-frameworklinqlinq-to-entitiesstrong-typing

How to join 2 tables using linq but avoid anonymous object


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)

Solution

  • 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.