开发者

EF4 inheritance and Stored procedures

开发者 https://www.devze.com 2023-01-29 06:33 出处:网络
I implemented inheritance with a discriminator field so all my records are in the same table. My basetype is Person (also the name of the table) 开发者_开发百科and Driver and Passenger inherit from it

I implemented inheritance with a discriminator field so all my records are in the same table. My basetype is Person (also the name of the table) 开发者_开发百科and Driver and Passenger inherit from it. I receive instances of the correct type (Driver and Passenger) when I perform a query on the object context to Person. example:

var q = from d in ctx.Person
        select d;

But I also create a function that calls a stored procedure and mapped the output of the function to the type Person. But now I get a list of Person and not Drivers or Passengers when I execute this method.

Anybody an idea how to solve this or is this a bug in EF4?


AFAIK, you can't use discriminator mapping (e.g TPH) when dealing with stored procedure mappings.

The stored procedure must be mapped to a complex type or custom entity (e.g POCO), the mapping cannot be conditional.

What you could do is map it to a regular POCO, but then project that result set into the relevant derived type (manual discrimination).

E.g:

public ICollection<Person> GetPeople()
{
   var results = ExecuteFunction<Person>(); // result is ObjectResult<Person>
   ICollection<Person> people = new List<Person>(); 

   foreach (var result in results)
   {
      if (result.FieldWhichIsYourDiscriminator == discriminatorForDriver)
      {
         people.Add((Driver)result);
      }

      // other discriminators
   }

}

If your always expecting a collection of one type (e.g only Drivers), then you wouldn't need the foreach loop, you could just add the range. The above is in case you are expecting a mixed bag of different people types.

Would be interested to see other answers, and if there is a better way though - but the above should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消