嗨。我有三个表,我也想对它们和子组进行分组。
Table Sections
-------------
Id
SectionName
Table Categories
-------------
Id
CategoryName
SectionRefId
Table Records
-------------
Id
RecordName
CategoryRefId
我想要实现的是将所有Category按SectionName分组,并将所有Records按CategoryName分组,并使用foreach循环显示它们。
I tried this using Linkpad the result it not what i exptected </p>
var result = from doc in Categories
group doc by doc.SectionRefId into docSections
select new
{
Name = docSections.Key,
Group = from dl in Records
group dl by dl.CategoryRefId into dlRecords
select new
{
Name = dlRecords.Key,
GroupRecords = dlocation
}
};
enter code here
答案 0 :(得分:0)
您可以执行此操作。需要一些加入和分组依据:
var result = from category in Categories
join section in Sections on category.Id equals section.ID
join record in Records on category.Id equals record.CategoryRefId
group category by {section.SectionName} into g
group record by {category.categoryName} into p
select new { CategoryName = g.Key.CategoryName, SectionName = section.SectionName, RecordName = record.RecordName };
答案 1 :(得分:0)
如果您遵循了entity framework code first conventions,则您的课程将拥有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