我有这个SQL查询,我需要转换为LINQ:
SELECT *
FROM USER U
INNER JOIN (
SELECT USERID , MAX(SALESDATE) AS MAXDATE
FROM SALES
GROUP BY USERID) S ON U.ID = S.USERID
到目前为止,这就是我提出的LINQ:
var Users = (from d in db.Users
join s in db.Sales on d.Id equals s.UserId
select new Models.User
{
Id = d.Id,
UserName = d.UserName,
FirstName = d.FirstName,
LastName = d.LastName,
EmailAddress = d.EmailAddress,
PhoneNumber = d.PhoneNumber,
LastPurchase = s.SalesDate
}).Max(x => x.SalesDate);
但是,我很确定结果不一样。任何人都可以建议将其转换为LINQ的正确方法吗?我还是学习LINQ的新手。我非常感谢你的帮助。
答案 0 :(得分:0)
试试这个
var Users = (from d in db.Users
from s in db.Sales.where(x=>x.Userid==d.id).groupby(x=>x.Userid)
select new Models.User
{
Id = d.Id,
UserName = d.UserName,
FirstName = d.FirstName,
LastName = d.LastName,
EmailAddress = d.EmailAddress,
PhoneNumber = d.PhoneNumber,
LastPurchase = s.Max(x=>x.SalesDate)
}).ToList();
答案 1 :(得分:0)
您当前的Linq查询,首先加入整个表,然后选择与您在Sales表中首先选择的SQL结果相反,然后加入该结果(示例中的别名S
)。
var query = from u in db.Users
join s in (from sale in db.Sales
group sale by sale.Id into grp
select new {
Id = grp.Key,
LastPurchase = grp.Max(item => item.SalesDate)
})
on u.Id equals s.Id
select /* what you need to retrieve */;
答案 2 :(得分:0)
你可以这样做:
var query1 = from sale in db.Sales
group sale by sale.UserId into g
let maxDate = g.Max(s => s.SalesDate)
select new { UserId = g.Key, maxDate };
var query2 = from user in db.Users
from q1 in query1.Where(q => q.UserId == user.Id)
select new { user.Id, user.UserName, user.Firstname, user.lastname, ... , q1.maxDate };
var result = query2.ToList();