Entity Framework - Selective Condition on Included Navigation Property

前端 未结 3 1770
花落未央
花落未央 2020-12-20 18:22

Assume I have these simplified EF generated entities...

public class PurchaseOrder
{
     public int POID {get;set;}
     public int OrderID         


        
3条回答
  •  鱼传尺愫
    2020-12-20 19:07

    You could use the IQueryable-Extensions here:

    https://github.com/thiscode/DynamicSelectExtensions

    The Extension builds dynamically an anonymous type. This will be used for projection as described by @Ladislav-Mrnka.

    Then you can do this:

    var query = query.SelectIncluding( new List>>>(){
    
    //Example how to retrieve only the newest history entry
    x => x.HistoryEntries.OrderByDescending(x => x.Timestamp).Take(1),
    
    //Example how to order related entities
    x => x.OtherEntities.OrderBy(y => y.Something).ThenBy(y => y.SomeOtherThing),
    
    //Example how to retrieve entities one level deeper
    x => x.CollectionWithRelations.Select(x => x.EntityCollectionOnSecondLevel),
    
    //Of course you can order or subquery the deeper level
    //Here you should use SelectMany, to flatten the query
    x => x.CollectionWithRelations.SelectMany(x => x.EntityCollectionOnSecondLevel.OrderBy(y => y.Something).ThenBy(y => y.SomeOtherThing)),
    
    });
    

提交回复
热议问题