user3004110
user3004110

Reputation: 969

How to join two tables in linq to entities

I am using inner join in linq to entities. I have to select all columns of both tables instead of writing one by one column manually. Below is my query please see the last line of code, I can only select c1 but not c2. How can I combine both c1 and c2 ???, Thanks in advance

using (var db = new POSContext())
{
    var query = (from c1 in db.LineMaster
                 join c2 in db.LineDetail on c1.OrderId equals c2.OrderId
                 where c1.OrderId == 123
                 select c1).ToList();
}

Upvotes: 2

Views: 6307

Answers (1)

alexmac
alexmac

Reputation: 19607

When you selecting only c1 or c2, EF creates anonymous object according the selected record. In the case, when you try to select c1 and c2, EF can't create anonymous object. You should create your own Model or anonimus object manually:

using (var db = new POSContext())
{
    var query = (from c1 in db.LineMaster
                join c2 in db.LineDetail on c1.OrderId equals c2.OrderId
                where c1.OrderId == 123
                select new 
                    {
                         IdC1 = c1.Id,
                         IdC2 = c2.Id,
                         // etc...  
                    }).ToList();
 }

Upvotes: 2

Related Questions