mercredi 18 juillet 2018

Add sort on reflected navigation property

I'm using EF 6.0 .NET-Framework and MS SQL Sever and I have the follow situation: I have a dynamic data selection on a Navigation property from a given entity. This works so far OK. But: I like to add some sortings. But I cannot figure out how to make EF understand, that the sort shall be sent to the database instead sorting on client side afterwards. The problem seems, that the data is requested from database when I retrieve the navigation property's value and not when I complete the command chain with the sort.

My code is like (simplyfied):

var dynamicRelatedEntityType = typeof(RelatedEntity);

using (var dbContext = new DBContext())
{
    var orderByFunction = buildOrderByFunction(dynamicRelatedEntityType ); // this just builds a function for the order by ...
    var masterEntity = dbContext.MasterEntity.first(x=> x.Whatever = true);
    var navigationProperty = masterEntity.GetType().GetProperty(dynamicRelatedEntityType.Name); 

    var result = navigationProperty.GetValue(masterEntity).OrderBy(orderByFunction).ToList();

    // result is OK, but sort wasn't sent to data base ... it was done by my program which is quite time expensive and silly too ...
}

So, how I can change this behaviour, any ideas? Thank you in advance!





Aucun commentaire:

Enregistrer un commentaire