Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.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
C# Sql查询到Linq到实体框架_C#_Mysql_Entity Framework_Linq - Fatal编程技术网

C# Sql查询到Linq到实体框架

C# Sql查询到Linq到实体框架,c#,mysql,entity-framework,linq,C#,Mysql,Entity Framework,Linq,我想知道是否有可能将下面的sql查询编写为LINQ to Entity语句。下面是一个简化的例子,我正试图找出一个现实世界中的问题: Select c.CustomerID, c.CustomerName, (Select count(p.ProductID) from Products p where p.CustomerID = c.CustomerID and p.Category = 'HomeAppliance') as ApplianceCount, (Select cou

我想知道是否有可能将下面的sql查询编写为LINQ to Entity语句。下面是一个简化的例子,我正试图找出一个现实世界中的问题:

Select
c.CustomerID,
c.CustomerName,
(Select count(p.ProductID) from Products p 
    where p.CustomerID = c.CustomerID and p.Category = 'HomeAppliance') as ApplianceCount,
(Select count(p.ProductID) from Products p
    where p.CustomerID = c.CustomerID and p.Category = 'Furnishing') as FurnishingCount
from Customer c
where 
c.CustomerMarket = 'GB'
order by c.CustomerID desc;
如有任何建议,将不胜感激。需要考虑LINQ to实体的性能,因为它将涉及检索大量行。

是的,可能:

customers
    .Where(cust => cust.CustomerMarket == "GB")
    .Select(cust => new
    {
        cust.CustomerId,
        cust.CustomerName,
        ApplianceCount = products
            .Where(prod => prod.CustomerId == cust.CustomerId && prod.Category == "HomeAppliance")
            .Select(prod => prod.ProductId)
            .Count(),
        FurnishingCount = products
            .Where(prod => prod.CustomerId == cust.CustomerId && prod.Category == "Furnishing")
            .Select(prod => prod.ProductId)
            .Count(),
    });
这里的
客户
产品
都是相应类型的
IQueryable
s。

类似于(假设明显的上下文):

需要考虑LINQTO实体的性能,因为它需要检索很多行


您需要确认生成的SQL是合理的(最好的帮助方法是不要得到比您需要的更多的列),然后性能将取决于服务器运行SQL的情况。

谢谢Richard。正是我想要的。我需要像“让”这样的东西,谢谢。但是我认为使用“let”可以更好地简化查询。我很确定它们的工作方式是相同的,所以这取决于您是否喜欢方法语法和查询语法。对我来说,在同一个地方混合使用这两种语言是很奇怪的,我个人的偏好是方法语法,这就是我这样写的原因,但当然,这可能不适用于你:)请不要只是发布SQL并要求转换。至少显示一个类模型,以便导航属性和关联的多样性可见。同时,展示你自己的第一次努力。他们向我们澄清的比你想象的要多。
var res = await (from c in dbCtx.Customers
                 where c.CustomerMarket = "GB"
                 let homeCount = c.Products.Where(p => p.Category = "HomeAppliance").Count()
                 let furnCount = c.Products.Where(p => p.Category = "Furnishing").Count()
                 orderby c.CustomerID descending
                 select new {
                   CustomerID = c.CustomerID,
                   CustomerName = c.CustomerName,
                   ApplianceCount = homeCount,
                   FurnishingCount = furnCount
                 }).ToListAsync();