Home > Enterprise >  EF Core 6 get the line with the max date by 2 columns
EF Core 6 get the line with the max date by 2 columns

Time:12-13

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. 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.

In the example below, I'd like the line 3

[data in database](https://i.stack.imgur.com/zL3Nk.png)

Could you help me to Group By 2 columns, and get the data?

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();

CodePudding user response:

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".

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.

CodePudding user response:

You need to create an anonymous object representing the group pair like this: 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). You can .GroupBy(x => x.MateriauID)

  • Related