Если вы следовали первым соглашениям кода инфраструктуры сущностей , ваши классы будут иметь virtual ICollection<...>
свойства, которые сделают группировку за вас:
class Section
{
public int Id { get; set; }
public string SectionName { get; set; }
// every section has zero or more Categories (one-to-many)
public virtual ICollection<Category> Categories {get; set;}
}
class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
// every Category belongs to exactly one Section using foreign key:
public int SectionId { get; set; }
public virtual Section Section {get; set;}
// every Category has zero or more Records (one-to-many)
public virtual ICollection<Record> Records {get; set;}
}
class Record
{
public int Id { get; set; }
public string RecordName { get; set; }
// every Record belongs to exactly one Category
public int CategoryId { get; set; }
public virtual Category Category {get; set;}
}
В структуре сущностей представлены столбцы таблиц базы данных.
по не виртуальным свойствам. Виртуальные свойства представляют
отношения между таблицами
Обратите внимание, что у вас могут быть разные идентификаторы для ваших таблиц и столбцов, главное, чтобы вы добавили виртуальные свойства
Я пытаюсь добиться того, чтобы сгруппировать все Category по SectionName и сгруппировать все Records по CategoryName и отобразить их с помощью цикла foreach.
var results = myDbContext.Sections
.Where (section => ...) // only if you don't want all Sections
.Select(section => new
{
// select only the properties you plan to use:
Id = section.Id,
Name = section.SectionName,
// This section has zero or more categories:
Categories = section.Categories
.Where(category => ...) // only if you don't want all categories
.Select(category => new
{
// again, select only the properties you plan to use:
Id = category.Id,
...
// not needed, you already know the value:
// SectionId = category.SectionId,
// this category has zero or more Records:
// you know the drill by now
Records = category.Records
.Where(record => ...)
.Select(record => new
{
Id = record.Id,
...
})
.ToList(),
})
.ToList(),
});
Платформа сущностей знает ваши отношения «один-ко-многим» и будет делать для вас нужные GroupJoins