c# - 如何使用 LINQ 查询包含多个子表?

标签 c# linq

我有这门课:

public class Word
{
    public string WordId { get; set; } // WordId (Primary key) (length: 20)
    public int WordIdentity { get; set; } // WordIdentity
    public virtual System.Collections.Generic.ICollection<WordForm> WordForms { get; set; } // WordForm.FK_WordFormWord
    public Word()
    {
        WordForms = new System.Collections.Generic.List<WordForm>();
    }
}

public class WordForm    {
    public string WordFormId { get; set; } // WordFormId (Primary key) (length: 20)
    public int WordFormIdentity { get; set; } // WordFormIdentity
    public string WordId { get; set; } // WordId (length: 20)
    public virtual System.Collections.Generic.ICollection<SampleSentence> SampleSentences { get; set; } // SampleSentence.FK_SampleSentenceWordForm
    public virtual System.Collections.Generic.ICollection<WordDefinition> WordDefinitions { get; set; } // WordDefinition.FK_WordDefinitionWordForm
    public WordForm()
    {
        SampleSentences = new System.Collections.Generic.List<SampleSentence>();
        WordDefinitions = new System.Collections.Generic.List<WordDefinition>();
    }
}

public class SampleSentence
{
    public int SampleSentenceId { get; set; } // SampleSentenceId (Primary key)
    public string WordFormId { get; set; } // WordFormId (length: 20)
    public string Text { get; set; } // Text

    // Foreign keys
    public virtual WordForm WordForm { get; set; } // FK_SampleSentenceWordForm
}

public class WordDefinition
{
    public int WordDefinitionId { get; set; } // WordDefinitionId (Primary key)
    public string WordFormId { get; set; } // WordFormId (length: 20)
    public string Text { get; set; } // Text (length: 50)
    public int? Ascii { get; set; } // Ascii

    // Foreign keys
    public virtual WordForm WordForm { get; set; } // FK_WordDefinitionWordForm
}

我正在尝试检索单词、wordForm、SampleSentences 和 WordDefinitions 的数据,但我不确定如何对选择进行编码。这是我到目前为止所拥有的:

var words = db.Words
            .Include(w => w.WordForms)
            // How do I include SampleSentences
            // and WordDefinitions ?
            .AsNoTracking()
            .ToListAsync();

有人可以告诉我如何包含 SampleSentences 和 WordDefinitions 吗?我尝试这样做,但语法检查失败:

 .Include(w => w.WordForms.SampleSentences)

最佳答案

只需在包含中使用 select 即可:

 .Include(w => w.WordForms.Select(f => f.SampleSentences))
 .Include(w => w.WordForms.Select(f => f.WordDefinitions))

关于c# - 如何使用 LINQ 查询包含多个子表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37247645/

相关文章:

c# - ${basedir} 位于何处,使用 NLog?

c# - 自动加载 32 位/64 位程序集

c# - LINQ First/FirstOrDefault 是否迭代整个可枚举?

C#高效存储大int数据

c# - 检查是否已使用具有相同值的属性

c# - ASP.NET 自定义控件属性访问

c# - linq lambda 多组连接

c# - Linq:搜索所有出现的多个空格的字符串

linq - 如何在 Entity Framework 7 (Core) 中按某些实体属性动态排序

c# - 加入 DataTables 通过 LINQ 获取新的 DataTable