A
A
Andrey2018-10-26 13:22:31
ASP.NET
Andrey, 2018-10-26 13:22:31

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

Here is a method that swears at me that I am casting List to IEnumerable
[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;
        }

Like Where returns IEnumerable...
Any advice would be welcome!
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey, 2018-10-29
@andrey71

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;
        }

Many thanks to everyone who helped me find a solution!

E
eRKa, 2018-10-26
@kttotto

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

then you can get grouped by key
and there will be a list

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question