views:

92

answers:

1

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 figured this out?

Thanks much.

+1  A: 

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.

Craig Stuntz
Thanks for the response, Craig. So far as you are aware, there is no way to accomplish what I'm asking without using projections? Or is that what you meant by "You can do this with entity types..."?
Daniel Pratt
I'm not really sure. But you can return entity types by projecting *those*. Because the Entity Framework fixes up references for all entities returned in a query, including an entity in one part of a projection will also make it show up in others. So if, for example, you project out the `Item` somewhere, it would also show up as a property of the `ItemOrderLine`.
Craig Stuntz