Mahdi jokar
Mahdi jokar

Reputation: 1267

select master with details fileds in linq

I want to select some of the Product's information after Category's infromation using linq to objects.

 var test = Context.Categories.Select(t => new { t.CategoryID, t.CategoryName });

How can i select Product's information. Category and Products have one-to-many relationship.

Upvotes: 0

Views: 1002

Answers (2)

Mahdi jokar
Mahdi jokar

Reputation: 1267

I found the answer , i use SelectMany() like this:

 var test = Context.Categories.SelectMany(t=>t.Products).Select(t => new { t.CategoryID, t.Category.CategoryName,t.ProductName });

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250176

You can do this using LINQ query syntax as well

var test = from c in Context.Categories
           from p in c.Products
           select new { c.CategoryID, c.CategoryName, p.ProductName });

Behind the scenes this is synonymous to :

var test = Categories.SelectMany
(
   c => c.Products, 
   (c, p) => new
   {
      c.CategoryID,
      c.CategoryName,
      p.ProductName
   }
);

Upvotes: 1

Related Questions