c# - Linq - EntityFramework NotSupportedException

标签 c# entity-framework linq entity-framework-6

我有一个如下所示的查询:

var caseList = (from x in context.Cases
         where allowedCaseIds.Contains(x => x.CaseId)
         select new Case {
            CaseId = x.CaseId,
            NotifierId = x.NotifierId,
            Notifier = x.NotifierId.HasValue ? new Notifier { Name = x.Notifier.Name } : null // This line throws exception
         }).ToList();

Case 类可以有 0..1 个 Notifier

上面的查询将导致以下 System.NotSupportedException:

Unable to create a null constant value of type 'Models.Notifier'. Only entity types, enumeration types or primitive types are supported in this context.

目前我发现的唯一解决方法是之后循环查询结果并手动填充 Notifier,如下所示:

foreach (var c in caseList.Where(x => x.NotifierId.HasValue)
{
    c.Notifier = (from x in context.Notifiers 
                 where x.CaseId == c.CaseId
                 select new Notifier {
                     Name = x.Name
                 }).FirstOrDefault();
}

但我真的不想这样做,因为在我的实际场景中它会生成数百个额外的查询。

对于这种情况,有什么可能的解决方案吗?。

最佳答案

我认为您需要分两步完成。首先,您可以在单个查询中使用匿名类型仅获取您需要的数据:

var caseList = (from x in context.Cases
     where allowedCaseIds.Contains(x => x.CaseId)
     select new {
        CaseId = x.CaseId,
        NotifierId = x.NotifierId,
        NotifierName = x.Notifier.Name
     }).ToList();

在那之后,你可以在内存中工作:

List<Case> cases = new List<Case>();
foreach (var c in caseList)
{
    var case = new Case();
    case.CaseId = c.CaseId;
    case.NotifierId = c.NotifierId;
    case.NotifierName = c.NotifierId.HasValue ? c.NotifierName : null;
    cases.Add(case);
}

关于c# - Linq - EntityFramework NotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014610/

相关文章:

c# - 排序一个字符数组,使所有元音都出现在最后

c# - Read() 仅接受第一个输入,但不接受来自其他 Console.Read() 的其他输入

c# - "Update-Database"命令失败并出现 TimeOut 异常

c# - 更新 Entity Framework 中的计算列

c# - 如何根据一个 LINQ 查询的结果过滤另一个查询的结果?

c# - 将特定数据从 1 个数据表传输到另一个错误

c# - 将 Rx 超时与 FromEventPattern Observer 结合使用

c# - 使用导航属性获取数据

c# - 在 C# 中从 Entity Framework 调用存储过程

c# - 为什么在 Select 之前运行 LINQ OrderBy 会花费更多时间?