开发者

LInq-to-sql dynamic sorting problem

开发者 https://www.devze.com 2022-12-18 00:55 出处:网络
I have a linq-to-sql query over entity that has child entityset that I need to sort on some child fields, i.e. use this query:

I have a linq-to-sql query over entity that has child entityset that I need to sort on some child fields, i.e. use this query:

开发者_JAVA技巧
   var query = from p in context.Patients 
            let order = p.Lab_Orders.First() 
            orderby order.Order_Date 
            select p; 

This query runs fine, but how would I modify it to use DLINQ OrderBy method what would I pass as a sorting parameter in run-time?


If by DLINQ you mean Dynamic Query, then you can't use the query expressions like that, you have to use extension methods with lambdas. You can start with a query expression but you have to eventually switch it over to lambda:

IEnumerable<Patient> GetPatients(string orderSortField)
{
    var query =
        from p in context.Patients
        select new
        {
            Patient = p,
            FirstOrder = p.Lab_Orders.First()
        };
    return p.OrderBy(orderSortField).Select(p => p.Patient);
}

Call it with:

var patientsByOrderDate = GetPatients("FirstOrder.Order_Date");


Use the AsQueryable() after the initial statement -

var query = from p in context.Patients
            let order = p.Lab_Orders.First()        
            select p; 

query = query.AsQueryable().OrderBy(x => x.Lab_Orders.First().OrderDate);


Try to add the "OrderBy" to the expression tree:

var query = from p in context.Patients 
            let order = p.Lab_Orders.First() 
            select p; 
var x = Expression.Parameter(query.ElementType, "x");
string sortName = "order.Order_Date";
var selector = Expression.Lambda(Expression.PropertyOrField(x, sortName), x);
query = query.Provider.CreateQuery(
         Expression.Call(typeof(Queryable), "OrderBy", 
              new Type[] { query.ElementType, selector.Body.Type },
               query.Expression, selector)
         ) as IQueryable<Patients>;

Needs the namespace "System.Linq.Expressions".

0

精彩评论

暂无评论...
验证码 换一张
取 消