Linq:链接的对象为空,为什么?
问题描述:
我有几个链接表(实体)。我试图让使用下面的LINQ实体:Linq:链接的对象为空,为什么?
ObjectQuery<Location> locations = context.Location;
ObjectQuery<ProductPrice> productPrice = context.ProductPrice;
ObjectQuery<Product> products = context.Product;
IQueryable<ProductPrice> res1 = from pp in productPrice
join loc in locations
on pp.Location equals loc
join prod in products
on pp.Product equals prod
where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1
select pp;
该查询返回2个记录已链接的对象位置和产品,ProductPrice对象,但它们是空的,我不明白为什么。如果我尝试,以填补他们在LINQ如下:
res =
from pp in productPrice
join loc in locations
on pp.Location equals loc
join prod in products
on pp.Product equals prod
where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1
select new ProductPrice
{
ProductPriceId = pp.ProductPriceId,
Product = prod
};
我也有例外,“实体或复杂类型‘PBExplorerData.ProductPrice’不能在LINQ构建以查询实体” 可能有人请给我解释一下发生了什么,我需要做什么? 谢谢
答
您的第一个问题的答案产品和位置为空,因为您需要为查询添加一个包含(“”)。
IQueryable<ProductPrice> res1 = from pp in
productPrice.Include("Location").Include("Product")
join loc in locations
on pp.Location equals loc
join prod in products
on pp.Product equals prod
where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1
select pp;
第二个问题是EF试图推低查询和ProductPrice(不是实体),所以它不能。如果你想这样做,将其转换为匿名类型所以只是做
select new
{
ProductPriceId = pp.ProductPriceId,
Product = prod
};
然后做
res.ToList().ConvertAll(x=new ProductPrice() {
ProductPriceId = x.ProductPriceId ,
Product = x.Product
});
或者你可以做其他的方式,选择您想要的实体,只是填充手册。
谢谢你的解决方案!尽管你的解决方案对我来说并不是最好的(我更喜欢使用延迟加载),但它让我明白了搜索的位置和搜索的内容。我发现可以使用主实体中的EntityReference的Load()方法进行延迟加载。 – mimic 2010-04-12 19:57:57