我有从基类“BaseTask”驱动的类
- 任务 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.
我该如何解决这个问题?
最佳答案
据我所知,这在 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#)。
关于c# - 无法将类型 'x' 转换为类型 'y'。 LINQ to Entities 仅支持转换 EDM 原语或枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46193587/