1

I have a linq query similar to the following that joins with the entity ProductCategories:

var list = from p in db.Products
           join pc in db.ProductCategories on p.ProductCategoryId equals pc.Id
           select new Product()
           {
              Id = p.Id, Name = p.Name, CategoryName = pc.Name
           };

Lets say I want to select p.* and in addition set the CategoryName navigation property from ProductCategories. Is this possibe? Or will I always have to specify everything when using navigation properties?

JTunney
  • 914
  • 1
  • 15
  • 46
  • 1
    Have a look [here](http://stackoverflow.com/questions/7861059/select-all-columns-after-join-in-linq), it's not quite a duplicate but it's a variation. – Rawling May 05 '15 at 14:54
  • So in my case would I just do select new { p.Id, p.Name, pc.Name } if I only needed those 3 properties and all of them were part of my Project object? – JTunney May 05 '15 at 14:58
  • Spot on, yeah! As long as you don't need the `*` you're OK. – Rawling May 05 '15 at 15:00
  • So lets say I do want to select all of product and in addition CategoryName what would I do? – JTunney May 05 '15 at 15:00

2 Answers2

2

Create an anonymous object and select your product object under one property and the category name under another property

select new 
       {
          Product = p, Name = p.Name, CategoryName = pc.Name
       };

enter image description here

mjroodt
  • 3,223
  • 5
  • 22
  • 35
0

The following should work as well if you want the entire thing, and your navigation properties are set up correctly (Make sure you have using System.Data.Entity; at the top of your file:

var list = db.Products.Include(p=>p.ProductCategories);

or a more simple anonymous class:

var list = db.Products.Select(p=>new { 
    p.Id,
    p.Description,
    ProductCategoryName=p.ProductCategories.Name});
Robert McKee
  • 21,305
  • 1
  • 43
  • 57