![](/img/trans.png)
[英]C# LINQ to Entities One-To-Many relationship: Problem displaying last log entry data
[英]LINQ join: selecting the last records in a one-to-many relationship
假設我有兩個表:
我正在嘗試 select 在某個日期時間(通常是 DateTime.Now)屬於某個部門的每個員工的最后一次簽名,因為我正在為我的公司開發一個基於考勤的應用程序。
到目前為止,我有以下查詢,它返回滿足先前條件(部門和時間)的所有員工的 EmployeeId 和 SignType。 我知道這個查詢應該有一個額外的連接(准確地說是左連接可能要感謝我昨天發現的這篇文章)但我真的不知道如何繼續,因為這是我第一次做這樣復雜的 linq 查詢。
非常感謝。
from e in AppDbContext.Employees
join s in AppDbContext.Signings
on e.EmployeeId equals s.EmployeeId
where e.DepartmentId == DepartmentId
&& s.Time.Date == DateTime.Now.Date
select new Aux2()
{
Id = e.EmployeeId,
Type = s.SignType,
};
編輯:子查詢嘗試
AppDbContext.Employees
.Where(e => e.DepartmentId == DepartmentId )
.Select(e => new Aux2(){
Id = e.EmployeeId,
Type = AppDbContext.Signings
.Where(s => s.EmployeeId== e.EmployeeId && s.Time.Date==Date)
.OrderByDescending(s => s.Time)
.Take(1)
.Select(s => s.SigType)
.FirstOrDefault()
})
你可以這樣做:
var maxDateSignsByEmployee = from sign in AppDbContext.Signings.Where(s => s.Time.Date == DateTime.Now.Date)
group sign by sign.EmployeeId into res
select new{
EmpId = res.Key,
MaxDate = resg.Max(x => x.Time)
};
var list = from e in AppDbContext.Employees
join s in AppDbContext.Signings.Where(s => maxDateSignsByEmployee.Where(m => m.EmpId == s.EmployeeId && m.MaxDate == s.Time).Count() > 0)
on e.WorkerId equals s.EmployeeId
where e.DepartmentId == DepartmentId
select new Aux2()
{
Id = e.EmployeeId,
Type = s.SignType,
};
它應該是你需要的。 這是一個基本的反應,你可以優化它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.