prefetching members of inherited entities via a LINQ-to-Entities query
I think the simplest way I can ask this question is with an example: Suppose that I have an Entity Framework model with an "Order" entity that has an "OrderLines" collection. The "OrderLines" collection is ostensibly a collection of OrderLine objects, but I am using inheritance here, so the actual type of an object in the collection is going to be NoteOrderLine, ItemOrderLine, etc. Furthermore, the ItemOrderLine entity has an associated "Item" entity.
What I want to be able to do is created a LINQ query based on the "Order" entity, prefetching the "OrderLines" collection, as well as prefetching the "Item" entity in the case that the "OrderLine" entity is actually of type "ItemOrderLine". Has anyone f开发者_运维技巧igured this out?
Thanks much.
You can do it with projection:
var q = from o in Context.Orders
select new
{
Customer = o.CustomerName,
Lines = from l in o.Lines
let i = l as ItemOrderLine
select new
{
Quantity = l.Quantity,
Item = i.Item.Name,
ItemNo = (int?) i.Item.Number // Note below
}
};
i
will be null when l
is of type NoteOrderLine
. Since int
is non-nullable, we must cast it to int?
so that the null i
can be coalesced when setting ItemNo
.
You can do this with entity types, too, but it's different. Since you give no example of the sort of code you're trying to write, I guessed.
精彩评论