LINQ,如何指定包含列表中的项目<&燃气轮机;

LINQ,如何指定包含列表中的项目<&燃气轮机;,linq,linq-to-sql,Linq,Linq To Sql,好的,我正在尝试从我的数据库中找到属于我提供的类别的所有子类别(使用查询结果成形)。“我的类”子类别包括一个类别列表 问题在于,在linq语句中,g指的是子类别(最终包含类别)。所以下面的陈述是不允许的 如何更改Linq语句以生成正确的SQL查询,以包含包含匹配类别的所有子类别 public class SubCategory { public int SubCategoryId { get; set; } public string Name { g

好的,我正在尝试从我的数据库中找到属于我提供的类别的所有子类别(使用查询结果成形)。“我的类”子类别包括一个类别列表

问题在于,在linq语句中,g指的是子类别(最终包含类别)。所以下面的陈述是不允许的

如何更改Linq语句以生成正确的SQL查询,以包含包含匹配类别的所有子类别

 public class SubCategory

    {
        public int SubCategoryId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<Article> Articles { get; set; }
        public List<Category> Categories { get; set; }
    }

//incorrect code below:
var SubCategories = storeDB.SubCategories.Include("Categories").Single(g => g.Name == category);
公共类子类别
{
公共int子类别ID{get;set;}
公共字符串名称{get;set;}
公共字符串说明{get;set;}
公共列表项目{get;set;}
公共列表类别{get;set;}
}
//下面的代码不正确:
var SubCategories=storeDB.SubCategories.Include(“Categories”).Single(g=>g.Name==category);

我发现每个子类别可以属于多个类别有点让人困惑——你是否正确处理了这种关系

无论如何,我认为如果您先将select更改为处理类别,可能会更具可读性,例如:

var subCatQuery   = from cat in storeDB.Categories
                    where cat.Name == category
                    select cat.SubCategories;
然后您可以执行该命令以获得IEnumerable:

我觉得这更容易理解


(我还发现这里的查询语法比fluent样式更容易阅读)

这对我来说很有用(可能太简单了):


我的首选答案是使用linq连接。如果只有2个数据集,则可以使用linq操作
.join
.groupjoin
与from语句。这就是我的方法

    Dictionary<MainQuery, List<subQuery>> Query = 
    dbStore.List<MainQuery>.include("IncludeAllObjects")
    .groupjoin(db.List<SubTable>.Include("moreSubQueryTables"), 
    mainQueryA=>mainQueryA.PropToJoinOn,
    subQueryB => sunQueryB.PropToJoinOn,
    ((main, sub)=> new {main, sub})
    .ToDictionary(x=>x.main, x=>x.sub.ToList());
字典查询=
dbStore.List.include(“includealObjects”)
.groupjoin(db.List.Include(“moreSubQueryTables”),
mainQueryA=>mainQueryA.PropToJoinOn,
subQueryB=>sunQueryB.PropToJoinOn,
((main,sub)=>new{main,sub})
.ToDictionary(x=>x.main,x=>x.sub.ToList());

实际上,子类别可以属于更多类别(例如:夹克衫属于猫男猫女,衬衫只属于猫女)。无论如何,您的更改会导致以下错误:{“传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery
1[System.Collections.Generic.List
1[Project1.Models.SubCategory]]',但此词典需要类型为“System.Collections.Generic.IEnumerable`1[Project1.Models.SubCategory].“}的模型项,听起来您还没有实际执行查询-我将添加一行。。。
var Category = storeDB.Categories.Include("SubCategories").Single(c => c.Name == category);
return Category.SubCategories;
    Dictionary<MainQuery, List<subQuery>> Query = 
    dbStore.List<MainQuery>.include("IncludeAllObjects")
    .groupjoin(db.List<SubTable>.Include("moreSubQueryTables"), 
    mainQueryA=>mainQueryA.PropToJoinOn,
    subQueryB => sunQueryB.PropToJoinOn,
    ((main, sub)=> new {main, sub})
    .ToDictionary(x=>x.main, x=>x.sub.ToList());