C
C#2y ago
no >> body

✅ Replacing Linq.Dynamic

I am trying to replace the System.Linq.Dynamic.Core package with regular LINQ in my ASP.NET Core application. I have a method that applies filtering, sorting, and pagination to a queryable collection of entities, using the System.Linq.Dynamic.Core package. Here is the code from my method:
if (!string.IsNullOrEmpty(filter))
{
var filterVal = (JObject)JsonConvert.DeserializeObject(filter);
var t = new T();
foreach (var f in filterVal)
if (t.GetType().GetProperty(f.Key)?.PropertyType == typeof(string))
entityQuery = entityQuery.Where($"{f.Key}.Contains(@0)", f.Value.ToString());
else
entityQuery = entityQuery.Where($"{f.Key} == @0", f.Value.ToString());
}

var count = entityQuery.Count();

if (!string.IsNullOrEmpty(sort))
{
var sortVal = JsonConvert.DeserializeObject<List<string>>(sort);
var condition = sortVal.First();
var order = sortVal.Last() == "ASC" ? "" : "descending";
entityQuery = entityQuery.OrderBy($"{condition} {order}");
}
if (!string.IsNullOrEmpty(filter))
{
var filterVal = (JObject)JsonConvert.DeserializeObject(filter);
var t = new T();
foreach (var f in filterVal)
if (t.GetType().GetProperty(f.Key)?.PropertyType == typeof(string))
entityQuery = entityQuery.Where($"{f.Key}.Contains(@0)", f.Value.ToString());
else
entityQuery = entityQuery.Where($"{f.Key} == @0", f.Value.ToString());
}

var count = entityQuery.Count();

if (!string.IsNullOrEmpty(sort))
{
var sortVal = JsonConvert.DeserializeObject<List<string>>(sort);
var condition = sortVal.First();
var order = sortVal.Last() == "ASC" ? "" : "descending";
entityQuery = entityQuery.OrderBy($"{condition} {order}");
}
I'm tried something like this
entityQuery = entityQuery.OrderBy(e => e.GetType().GetProperty(condition).GetValue(e));
entityQuery = entityQuery.OrderBy(e => e.GetType().GetProperty(condition).GetValue(e));
But this obviously doesn't work. Is there a way to sort a queryable collection of entities based on a property, using regular LINQ and Entity Framework Core? Downloading all entities to the memory and sorting them in the asp.net core app is not an option.
4 Replies
Angius
Angius2y ago
collection.OrderBy(thing => thing.Property)
no >> body
no >> bodyOP2y ago
I wish it could be so easy. I'm dealing with a generic method.
Angius
Angius2y ago
So? Whatever you're sorting, you sort it by something So pull that property out to an interface, for example Add a generic constraint to that interface And order by that property
no >> body
no >> bodyOP2y ago
I know. But the problem is that this method is entirely generic. The constraints it has is class and new(). That's all that I know about the type. But anyway, I decided to make this method in another way. This question is not relevant anymore.
Want results from more Discord servers?
Add your server