I have a Linq To Entities query I am making in my POCO Entity Framework application, that looks like this:
var orders = stateRepository.Get()
.OfType<OrderedState>()
.Where(x => x.Id == stateId)
.Include(x => x.Order);
return orders.FirstOrDefault();
The OfType
there is because the State entities use Table Per Hierarchy inheritance. Only OrderedState
and its children have the Order
property available to them.
However, when I run it, I hit the following error:
An object of type 'System.Data.Entity.DynamicProxies.OrderedState_6F372135E57CB68DDA1A42541A941E1F0848887EABD8BD4833D0159C9D8B055F' cannot be added, attached, or removed from an EntityCollection that contains objects of type My.NameSpace.Entities.OrderedState'."
Is this because EntityFramework is being confused by the fact that OrderedState
inherits from OrderState
and shares common properties, which are what I am interested in? If I remove the .Include(x => x.Order)
from the Linq statement the error is avoided, but the Order itself related to this State comes back as null when my entire purpose is to retrieve precisely that value.
Edit: With more research I have realised something even weirder is going on. My TPH inheritance hierarchy is like this:
BasicState
has many -> StatefulEntities
has a -> CreationDate
LocationState : BaseState
has a -> EntityLocation
ReceivedState : LocationState
has a -> ReceivedDate
ApprovedState : LocationState
has a -> ApprovedBy
OrderedState
has a -> Order
DispatchedState : OrderedState
has a -> DispatchNumber
So when I seek an OrderedState
it could be either an OrderedState or A DispatchedState but what I am interested in doing is loading the Order
property, which I can't do if I have an untyped list of BaseState objects.
What I am now realising is that when I have the .Include( x => x.Order)
Entity Framework ignores the type argument. This got clearer as I tweaked my seed data and started getting this type of error message:
An object of type 'System.Data.Entity.DynamicProxies.ReceivedState_6F372135E57CB68DDA1A42541A941E1F0848887EABD8BD4833D0159C9D8B055F' cannot be added, attached, or removed from an EntityCollection that contains objects of type My.NameSpace.Entities.OrderedState'."
I was surprised by this so I thought I would try reinforcing the type:
var orders = stateRepository.Get()
.OfType<OrderedState>()
.Where(x => x is OrderedState && x.Id == stateId )
.Include(x => x.Order);
Sure enough, when I don't try to include the Order
property I get only OrderedStates back. As soon as I use Include
I get an exception because the types that I am deliberately trying to avoid returning cannot be returned. The Id I am querying is definitely the ID of an OrderedState- in fact the method I am calling only accepts OrderedState objects as yet as a test to see whether that would prevent this problem.
My goal is to retrieve a single typed element from the TPH table including the child property that only this typed element will have.