问题描述
我有问题
public class Category : IId
{
[Key] public int Id { get; set; }
[required] public string Name { get; set; }
public List<SubToCat> SubToCat { get; set; }
}
和子类别实体类:
public class SubCategory : IId
{
[Key] public int Id { get; set; }
[required] public string Name { get; set; }
public List<SubToCat> SubToCat { get; set; }
}
及其我的 SubToCat 实体类:
public class SubToCat
{
public int SubCategoryId { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
public SubCategory SubCategory { get; set; }
}
现在在所有 SubCategory 的 Get 方法中,我想加入其 CategoryId 与 CategoryId 相同的所有类别 但我不知道怎么做,你能帮帮我吗
解决方法
我假设您正在使用一些实体框架:
_dbContext.SubCategories.Where(s => s.SubToCat.Category == CategoryId)
,
您不需要加入。只需使用 SelectMany 作为以下代码:
class Program
{
static void Main(string[] args)
{
DataContext db = new DataContext();
var results = db.Category.SelectMany(x => x.SubToCat.SelectMany(y => y.SubCategory.SubToCat.Select(z => new {
catId = x.Id,catName = x.Name,subToSubCatId = y.SubCategoryId,subToCatId = y.CategoryId,subToCategory = y.Category,subToCatSubCatId = z.SubCategory.Id,subToCatSubCatName = z.SubCategory.Name
}).ToList():
}
}
public class DataContext
{
public List<Category> Category { get; set; }
}
public class IId
{
}
public class Category : IId
{
public int Id { get; set; }
public string Name { get; set; }
public List<SubToCat> SubToCat { get; set; }
}
public class SubCategory : IId
{
public int Id { get; set; }
public string Name { get; set; }
public List<SubToCat> SubToCat { get; set; }
}
public class SubToCat
{
public int SubCategoryId { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
public SubCategory SubCategory { get; set; }
}
,
试试
_dbContext.SubCategories
.Include(x => x.SubToCat)
.Include(x => x.Category)
这将使用 2 个连接在单个 SQL 查询中引入所有子类别以及连接表和相关类别。