I have a linq query similar to the following that joins with the entity ProductCategories:
我有一个类似于以下连接实体ProductCategories的linq查询:
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?
假设我想选择p。*并另外设置ProductCategories的CategoryName导航属性。这可能吗?或者在使用导航属性时是否总是必须指定所有内容?
2 个解决方案
#1
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
};
#2
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:
如果您想要整个内容,并且您的导航属性设置正确,则以下内容也可以正常工作(确保您使用的是System.Data.Entity;位于文件顶部:
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});
#1
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
};
#2
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:
如果您想要整个内容,并且您的导航属性设置正确,则以下内容也可以正常工作(确保您使用的是System.Data.Entity;位于文件顶部:
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});