2017-09-13 26 views
1

我有从基类驱动类 “BaseTask无法将类型'x'转换为输入'y'。 LINQ到实体仅支持浇铸EDM原语或枚举类型

  • 任务1
  • 任务2
  • 任务3

    return DbContext.Projects.Include(t => t.Tasks).Select(p => new ProjectDto 
        { 
         Id = p.Id, 
         Name = p.Name, 
         Tasks = p.Tasks.Select(t => new TaskDto() 
         { 
          Id = t.Id, 
          Name = t.Name, 
          ProjectId = t.ProjectId, 
          Selector = !(t is Task1) ? t.Selector : null, 
          Task2Property = (t is Task2) ? ((Task2)t).Task2Property : null, 
          SelectorPosition = (t is Task3) ? ((Task3)t).SelectorPosition : null, 
          KeyId = t.KeyId 
         }).ToList() 
        } 
        ); 
    

这部分代码返回以下错误:

Unable to cast the type 'Task' to type 'Task1'. LINQ to Entities only supports casting EDM primitive or enumeration types.

我该如何解决这个问题?

+0

Materialiaing'IQueryable'后执行DTO转换工作谢谢 – ASpirin

回答

1

AFAIK EF不可能这样做,因为EF无法将其转换为SQL。但也许一个小的结构变化将有助于:

return DbContext.Projects.Include(t => t.Tasks).Select(p => new ProjectDto 
    { 
     Id = p.Id, 
     Name = p.Name, 
     Tasks = p.Tasks.Select(t => new TaskDto() 
     { 
      Id = t.Id, 
      Name = t.Name, 
      ProjectId = t.ProjectId, 
      Task = t, 
      KeyId = t.KeyId 
     }).ToList() 
    }); 

,并在TaskDto

public X Selector => (Task as Task1)?.Selector; 
public X Task2Property => (Task as Task2)?.Task2Property; 
public X SelectorPosition => (Task as Task3)?.SelectorPosition; 

哪里X是合适的类型,每个属性(和=>{ get { return x; } }的缩写形式,如果你还在使用旧版本的C#)。

+0

感谢 – akd

相关问题