[英]EF Core 6 get the line with the max date by 2 columns
I'm a beginner in EF Core, I have a table with some production with a height, each time the weight change, we inserted a line in the database.我是 EF Core 的初学者,我有一个表,其中包含一些具有高度的产品,每次重量变化时,我们都会在数据库中插入一行。 I just need to get the last weight.
我只需要得到最后的重量。
Here is my model这是我的模型
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; }
}
For example, I'd like to get, for a lotID-MateriauID the data for the max dateProd.例如,对于 lotID-MateriauID,我想获取最大 dateProd 的数据。
In the example below, I'd like the line 3在下面的示例中,我想要第 3 行
[data in database] ( https://i.stack.imgur.com/zL3Nk.png ) [数据库中的数据] ( https://i.stack.imgur.com/zL3Nk.png )
Could you help me to Group By 2 columns, and get the data?你能帮我按 2 列分组,并获取数据吗?
Thanks a lot非常感谢
I've tried this code:我试过这段代码:
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();
I don´t think you are looking to group by
if you want to " get, for a lotID-MateriauID the data for the max dateProd ".如果您想“获取 lotID-MateriauID 最大 dateProd 的数据”,我不认为您正在寻找
group by
。
You could instead:你可以改为:
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.
You need to create an anonymous object representing the group pair like this: new { x.LotID, x.MateriauID }
您需要像这样创建一个代表组对的匿名对象:
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();
But you actually don't need to group by both fields as you have already filtered with .Where(b => b.LotID == LotID)
.但是您实际上不需要按这两个字段进行分组,因为您已经使用
.Where(b => b.LotID == LotID)
进行了过滤。 You can .GroupBy(x => x.MateriauID)
你可以
.GroupBy(x => x.MateriauID)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.