P
P
Philip Bondarev2019-07-19 12:30:59
C++ / C#
Philip Bondarev, 2019-07-19 12:30:59

How to declare a variable to hold the result of a GroupBy() done in EF Core outside of the current class?

EF Core - there is a selection from the database:

var transactions = _context.Transactions
    .Include(s=>s.Buyer)
    /*...*/
    .Select(s=>new
    {
        TransactionId = s.Id,
        BuyerName = s.Buyer.Name,
        /*...*/
    })
    .ToListAsync();

Next, I need to package the received data into different groups, and then each subgroup into some more groups, and so on. (as a result, such a graph is obtained). So, I do the first grouping for the root list:
// Для примера возьмем корневой категорией - Тип транзакции
// В дальнейшем он может быть произвольным
var groupedTransactions = transactions.GroupBy(s => s.TransactionType);
foreach (var group in groupedTransactions )
{
    var newGroup = new GroupReportCategoryDto();
    newGroup.Id = 1;
    newGroup.Count = group.Count();
    newGroup.TransactionsGroupedByCategory = group;
    newReport.Categories.Add(newGroup);
}

newReport is a DTO class with an array of root elements:
public class GroupReportDto
{
    public ICollection<GroupReportCategoryDto> Categories { get; set; }
}

, and GroupReportCategoryDto :
public class GroupReportCategoryDto
{
    public int Id { get; set; }
    public int Count { get; set; }
    public ICollection<GroupReportCategoryDto> SubCategories { get; set; }

    // Тут я решил хранить сгруппированные транзакции для текущей
    // категории, чтоб в последствии из них делать следующие подгруппы
    public IGrouping<string, dynamic> StudiesGroupedByCategory { get; set; }

    public void SetSubCategories(int categoryId)
    {
        // Опустил тут switch/case по передаваемому типу,
        // потом, скорее всего, буду Expression передавать.

        // Вот тут проблема, пишет, что:
        // RuntimeBinderException: 'object' does not contain a definition for 'Sex'
        var groupedStudies = TransactionsGroupedByCategory.GroupBy(s => s.Sex);
        foreach (var group in groupedTransactions)
        {
                var newGroup = new GroupReportCategoryDto();
                newGroup.Id = 6;
                newGroup.Count = group.Count();
                SubCategories.Add(newGroup);
        }
    }
}

the question is how to declare TransactionsGroupedByCategory in GroupReportCategoryDto so that it sees the necessary properties? Moreover, I look in breakpoints - everything is normal, the types are the same.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question