[英]EF Core 6 get the line with the max date by 2 columns
我是 EF Core 的初學者,我有一個表,其中包含一些具有高度的產品,每次重量變化時,我們都會在數據庫中插入一行。 我只需要得到最后的重量。
這是我的模型
public class Prod
{
[Required]
public int ProdID { get; set; } (key)
public int LotID { get; set; }
public int MateriauID { get; set; }
public float? Weight{ get; set; }
public DateTime? DateProd { get; set; }
public Lot? Lot { get; set; }
public Materiau? Materiau { get; set; }
}
例如,對於 lotID-MateriauID,我想獲取最大 dateProd 的數據。
在下面的示例中,我想要第 3 行
[數據庫中的數據] ( https://i.stack.imgur.com/zL3Nk.png )
你能幫我按 2 列分組,並獲取數據嗎?
非常感謝
我試過這段代碼:
var prod = _context.Prods.Include(x => x.Materiau)
.Include(y => y.Lot)
.Where(b => b.LotID == LotID);
var prodMax = prod.GroupBy(x => x.LotID, x=>x.MateriauID)
.Select(s => s.OrderByDescending(x => x.dateProd).First())
.ToListAsync();
如果您想“獲取 lotID-MateriauID 最大 dateProd 的數據”,我不認為您正在尋找group by
。
你可以改為:
var res = myDbSet
.OrderByDescending(x => x.DateProd) // Order by latest date first.
.Select(x => new { LotId = x.LotID, MateriauId = x.MateriauID }) // Select the values you want, here as an anonymous object.
.FirstOrDefault(); // Materialize the query by picking the first one - e.g. the one with the latest date.
您需要像這樣創建一個代表組對的匿名對象: new { x.LotID, x.MateriauID }
var prod = _context.Prods.Include(x => x.Materiau)
.Include(y => y.Lot)
.Where(b => b.LotID == LotID);
var prodMax = prod.GroupBy(x => new {x.LotID, x.MateriauID})
.Select(s => s.OrderByDescending(x => x.dateProd).First())
.ToListAsync();
但是您實際上不需要按這兩個字段進行分組,因為您已經使用.Where(b => b.LotID == LotID)
進行了過濾。 你可以.GroupBy(x => x.MateriauID)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.