views:

9

answers:

1

If I have entities that inherit from a base entity (say "Widgets", "Gadgets", and "Gizmos" inherit from "Device") and I want to query Devices and return the specific type of each item in the resulting projection, like so:

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

Which would return a list like:

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

Of course, EF complains because GetType() is not a SQL Server cannonical function. Is there a way to do this?

+1  A: 

There are two ways. If there's only a few types involved, you can do:

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

Ugly, but necessary in cases.

Alternately, go into L2O:

(from d in Devices
 select new
 {
    Name = d.Name,
    Obj = o
 }).AsEnumerable()
   .Select(
     d => new 
          {
              Name = d.Name,
              Type = d.GetType()
          });
Craig Stuntz
First method worked fine, as I have a finite number of known types and do not want to enumerate the data.
CodeGrue