Entity structure and dynamic order by operators

I'm struggling to get this to work. I want the EF instruction to be accepted in the order column. My initial expression was as follows:

var Query = from P in DbContext.People
                   where P.BusinessUnits.Any(BU =>BU.BusinessUnitID == businessUnitId)
                   orderby P.LastName
                   select P;

And I changed this to the following:

var Query = from P in DbContext.People
                   where P.BusinessUnits.Any(BU =>BU.BusinessUnitID == businessUnitId)
                   orderby sortField
                   select P;

Where sortFieldis the column that we want to sort, and is the row, that is LastName. However, it does not work, it does not sort, and the output SQL string is completely incorrect. Has anyone got this job before?

+5
source share
2 answers

you can try passing the expression to your method with the following type:

Expression<Func<Person, object>> expr = p => p.LastName;

and then using linq extensions instead of linq expressions ...

var Query = 
 DbContext.People
 .Where(P => P.BusinessUnits.Any(BU =>BU.BusinessUnitID == businessUnitId))
 .OrderBy(expr)
 .ToList();
+11
source

, . , . API IQueryable<T>, , :

var q = from P in DbContext.People
   where P.BusinessUnits.Any(BU =>BU.BusinessUnitID == businessUnitId)
   orderby P.LastName
   select P;
if ("sortField".Equals("FirstName"))
    q = q.OrderBy(p => p.FirstName);
else if ("sortField".Equals("LastName"))
    q = q.OrderBy(p => p.LastName);
else if ("sortField".Equals("Dob"))
    q = q.OrderBy(p => p.Dob);
+3

All Articles