[英]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.