Dynamically sorting and filtering projected Entity SQL results
-
27-09-2019 - |
Question
I have the following query which I want to sort or filter using projected class names:
List<CompanyInfo> list = new List<CompanyInfo>();
using (var db = new DbContext())
{
list.AddRange(
db.Companies.Include("Projects")
.Select(row => new CompanyInfo()
{
ProjectCount = (from s in row.Projects
where s.Company.fId == row.fId
select s.pId).Count(),
Id = satir.fId,
})
//.OrderBy("ProjectCount") //<== what I want to do
);
}
I want to dynamically order this query using ProjectCount
or Id
columns same as ESQL, like .OrderBy("ProjectCount")
. Since the query result is IQueryable instead of ObjectContext it doesn't work. Is there a way to do this?
Solution 4
Thanks for the replies, I used helper extension methods:
OTHER TIPS
You should be able to do it like this: .OrderBy(p => p.ProjectCount)
Take a look at the Dynamic LINQ library.
Here is a tutorial that seems to describe your case.
You can do some nifty things with LINQ, if you know what to do. Maybe something like this??
var query = db.Companies.Include("Projects").Select(row =>
new CompanyInfo()
{
ProjectCount = (from s in row.Projects where s.Company.fId == row.fId select s.pId).Count(),
Id = satir.fId,
});
if (orderBy) // orderBy is bool, that tels you what to order by
query = query.OrderBy(x => x.ProjectCount);
else
query = query.OrderBy(x => x.Id);
list.AddRange(query);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow