繁体   English   中英

EF 核心 ThenInclude Select 说“Include 中使用的 Lambda 表达式无效”

[英]EF core ThenInclude Select says "Lambda expression used inside Include is not valid"

var test = await Db.Tests.Include(test => test.Questions)
                            .ThenInclude(ques => ques.Choices.Select(
                                ch => new {
                                    ch.Id, ch.OptionName, 
                                    ch.OptionText, ch.OptionDetails, 
                                    ch.IsAnswer, ch.QuestionId
                            })).AsNoTracking()
                            .FirstOrDefaultAsync(z => z.TestId == testId);

没有Select子句它工作正常。 但是我不需要所有的Choices属性,所以我尝试使用Select子句来选择一些属性。

它通过这个错误:

System.InvalidOperationException:Include 中使用的 Lambda 表达式无效。

有人能告诉我这里有什么问题吗?

我想你想要这样的东西:

var test = await Db.Tests
    .Where(test => test.TestId == testId)
    .Include(test => test.Questions) // Shouldn't need this
    .ThenInclude(ques => ques.Choices) // Shouldn't need this
    .SelectMany(test => test.Questions.SelectMany(ques => ques.Choices.Select(ch => new {
        ch.Id,
        ch.OptionName, 
        ch.OptionText,
        ch.OptionDetails, 
        ch.IsAnswer,
        ch.QuestionId
    }))))
    .AsNoTracking();

这将为您提供特定测试的所有选择。

但是...由于您将结果具体化为 lambda,您实际上不应该需要Include (EF 会发出警告,说它无论如何都忽略了您在控制台中的Include )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM