Answer the question
In order to leave comments, you need to log in
.NET Core Web Api EF How to group values in a query?
Good day everyone!
Please tell me, I recently started studying asp.net core + EF pulled myself up ... I still don’t understand everything, I’m trying to make a selection from the database with a grouping of the result. I need to select all rows with a certain code and group them by product name (Nomenklatura).
The model is like this:
public class Orders
{
public int Id { get; set; }
public int Kod { get; set; }
public string Nomenklatura { get; set; }
public int Kolich { get; set; }
}
[HttpGet]
public IEnumerable<Orders> Get([FromQuery(Name = "kod")]int kod)
{
var orders = db.Orders
.Where(x => x.Kod == kod)
.GroupBy(x => x.Nomenklatura).ToList();
return orders;
}
Answer the question
In order to leave comments, you need to log in
Here is the code that was suggested to me that gives the desired result:
GET localhost:65171/api/orders/966
[
"Перчатки",
"Варежки"
]
public IEnumerable<string> GetNomenklatura(int kod)
{
var orders = db.Orders
.Where(x => x.Kod == kod)
.GroupBy(x => x.Nomenklatura)
.Select(x => x.Key)
.ToList();
return orders;
}
GroupBy will essentially return an array of arrays to you, you cannot bring it to a List, you can lead it to a Dictionary, for example
var orders = db.Orders
.Where(x => x.Kod == kod)
.GroupBy(x => x.Nomenklatura)
.ToDictionary(x => x.FirstOrDefault().Nomenklatura, x => x.ToList() )
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question