Linq2EF在查询投影中返回子类的类型

时间:2010-08-19 17:55:44

标签: linq-to-entities

如果我有从基础实体继承的实体(比如“Widgets”,“Gadgets”和“Gizmos”继承自“Device”),我想查询Devices并返回结果中每个项目的特定类型投影,像这样:

from d in Devices
select new
{
   Name = d.Name,
   Type = d.GetType()
};

哪会返回如下列表:

Spring, Widget
Gear, Gizmo
Tape, Gadget
Scissors, Gizmo
Screw, Widget

当然,EF抱怨因为GetType()不是SQL Server的非常规函数。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

有两种方法。如果只涉及几种类型,您可以这样做:

from d in Devices
let typeName = d is Spring ? "spring" : d is Widget ? "widget" : "etc."
select new
{
   Name = d.Name,
   Type = typeName
};

丑陋,但在案件中是必要的。

或者,进入L2O:

(from d in Devices
 select new
 {
    Name = d.Name,
    Obj = o
 }).AsEnumerable()
   .Select(
     d => new 
          {
              Name = d.Name,
              Type = d.GetType()
          });