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

时间:2016-05-16 06:04:48

标签: 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
}

我试图检索word,wordForm,SampleSentences和WordDefinitions的数据,但我不知道如何编写select。这就是我到目前为止所拥有的:

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

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

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

1 个答案:

答案 0 :(得分:3)

只需在include中使用select:

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