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)
3
  • I suspect error is because of types used join condition, can you check both Ids are of same type? Commented Jan 29, 2016 at 5:37
  • You notice error in foreach because the first statement is deferred exectution. Commented Jan 29, 2016 at 5:38
  • They are same types (integer). query statement not throwing the error. foreach execution throws the error. Commented Jan 29, 2016 at 5:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. it works!. i just wondering "linq query" syntax for, first return anonymous type and convert it to tuple. (optional & googled) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.