C# 动态Linq到实体框架

C# 动态Linq到实体框架,c#,entity-framework,linq,C#,Entity Framework,Linq,有没有办法更改Linq语句对Where和OrderBy的作用 我尝试使以下示例函数更灵活: public static List<SADatastore.SA_Items> BuildResourcesModel2( int Take = 10000, int Skip = 0, string filterBy = null, string filterString = null, string sort

有没有办法更改Linq语句对Where和OrderBy的作用

我尝试使以下示例函数更灵活:

public static List<SADatastore.SA_Items> BuildResourcesModel2(
        int Take = 10000,
        int Skip = 0,
        string filterBy = null,
        string filterString = null,
        string sortBy = "ItemID",
        string sortOrder = "asc"
        ) {

        List<SADatastore.SA_Items> theAnswer = new List<SA_Items>();

        using (SADatastoreEntities db = new SADatastoreEntities(Properties.Settings.Default.ConnectionString)) {
            theAnswer = db.SA_Items
                        .Where(x => x.SA_Categories.Description.ToLower().Contains(filterString.ToLower()))
                        .OrderBy(x=>x.ItemID)
                        .Take(Take)
                        .Skip(Skip)
                        .ToList();
        }

        return theAnswer;
    }
它将动态地更改Where和Order子句


任何帮助都将不胜感激

分解linq查询:

var items = db.Items.Where(x => x.CategoryName == "Category A");

if (sortOrder == "desc") items = items.OrderByDesc(x => x.Id);
else items = items.OrderBy(x => x.Id);

return items.ToList();

您应该能够通过使用反射来实现这一点

x.SA_Categories.GetType().GetProperty(filterby).GetValue(x);  //this gets you the value of the property you're filtering by.  

发布了类似的情况

你看到这篇SO帖子了吗?SO上有很多类似的问题(分别用于筛选和排序),以及解决方案-从动态LINQ包开始,通过
System.LINQ.expressions.Expression
类方法动态构建表达式。您可以使用反射做几乎任何事情。但这并不意味着你应该这么做。
x.SA_Categories.GetType().GetProperty(filterby).GetValue(x);  //this gets you the value of the property you're filtering by.