Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linq到实体优化_Linq_Entity Framework - Fatal编程技术网

Linq到实体优化

Linq到实体优化,linq,entity-framework,Linq,Entity Framework,我有以下linq到实体查询 from p in Products where p.ProductId==1219 select new { Name = p.ProductName, count = (from dc in DiscountCodes where dc.ProductId == p.ProductId select dc).Count() } 现在生成的sql是(使用linqpad) 这似乎不是很有效,尤其是当我需要开始在相关表上

我有以下linq到实体查询

from p in Products
where p.ProductId==1219
select new
{
    Name = p.ProductName,
    count = (from dc in DiscountCodes
        where dc.ProductId == p.ProductId
        select dc).Count()
}
现在生成的sql是(使用linqpad)

这似乎不是很有效,尤其是当我需要开始在相关表上添加更多计数时

有没有更好的方法来优化此查询


谢谢

我想您在
折扣编码
产品
表之间有一种关系。我的意思是
DiscountCodes
表有
ProductId
ForeignKey

那么这应该更好

from p in Products
where p.ProductId==1219
select new
{
    Name = p.ProductName,
    Count = p.DiscountCodes.Count,
}

实体框架通过父表和子表的外键关系创建它们之间的关系。所以在这种情况下,下面的查询应该适合您

from p in Products
where p.ProductId==1219
select new
{
    Name = p.ProductName,
    count = p.DiscountCodes.Count()
}

谢谢我设置了关系,但是仍然生成相同的sql。我只是想知道这是否是最优化的sql?在sql中,哪种方法更有效?@lazyberezovsky我不确定,我想知道是否有更有效的方法?
Count
是一种方法,而不是属性。实际上,它是IEnumerable的扩展方法,ICollection的属性。它仍然是一种方法。实际上,在这种情况下,它是
IQueryable
的一个扩展方法,我坚持它是ICollection接口中的一个属性:)可以这样调用:)同意,导航属性的类型是
ICollection
:)现在我很感兴趣,这个属性是否立即执行,或者它被翻译成
IQueryable
call。。
from p in Products
where p.ProductId==1219
select new
{
    Name = p.ProductName,
    count = p.DiscountCodes.Count()
}