entity framework - how can I implement this SQL in the abbreviated EF linq

☆樱花仙子☆ 提交于 2019-12-24 00:19:08

问题


Can anyone help out with what the C# code would be to implement this SQL as Entity Framework Linq in the abbreviated form? (e.g. where you have the "." notation such as xxx.where(... etc)

SELECT PN.Name, Sum(U.Amount)
FROM Usages as U, ProcessNames as PN
WHERE PN.Id == U.ProcessNameId 
   AND U.Datetime BETWEEN '2010-01-08' AND '2010-10-11'
Group By PN.Name

回答1:


Method-Based Query:
To implement this in lambda we need to leverage Queryable.GroupJoin:

var query = context.ProcessNames
    .GroupJoin(context.Usages
                      .Where(u => u.Datetime >= new DateTime(2010, 1, 8) ) 
                                  && u.Datetime <= new DateTime(2010, 10, 11),
               pn  => pn.Id,
               u => u.ProcessNameId, 
               (pn, usages) => new { Name = pn.Name, 
                                     Sum = usages.Sum(u => u.Amount) });


Query Expression:
And the very same query in query expression syntax:

var query = 
    from pn in context.ProcessNames
    join u in context.Usages
                     .Where(u => u.Datetime >= new DateTime(2010, 1, 8) ) 
                                 && u.Datetime <= new DateTime(2010, 10, 11),
    on pn.Id 
    equals u.ProcessNameId 
    into g                      
    select new { Name = pn.Name, 
                 Sum = g.Sum(u => u.Amount) };


Check the Generated SQL:
To verify that these queries give you your desired Sql command at runtime you can do this:

string sqlCommand = ((ObjectQuery)query).ToTraceString();


More Examples:
For some good examples on GroupJoin, please take a look at these:

Method-Based Query Syntax Examples: Join Operators
Query Expression Syntax Examples: Join Operators




回答2:


Try this (I don't have your code so I'm getting no compiler help):

from u in context.Usages
join pn in context.ProcessNames on pn.Id equals u.ProcessNameId
where u.Datetime >= new DateTime(2010, 1, 8) && u.Datetime <= new DateTime(2010, 10, 11)
group pn by pn.Name into g
select new { Name = pn.Name , sum = g.Sum(u => u.Amount) };

That is the query expression version of it. To get the lambda based syntax (as I believe you are asking for this question), put the query into LinqPad and run it. Then click on the lambda tab in LinqPad and it will show you that syntax of the above query as if you had written it with lambda expressions (i.e., where you have the "." notation) and not a query expression.



来源:https://stackoverflow.com/questions/3887188/entity-framework-how-can-i-implement-this-sql-in-the-abbreviated-ef-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!