简体   繁体   English

C#,Linq,动态查询:用于过滤存储库外部的动态查询的代码

[英]C#, Linq, Dynamic Query: Code to filter a Dynamic query outside of the Repository

If you do something like this in your Repository: 如果您在存储库中执行以下操作:

IQueryable<CarClass> GetCars(string condition, params object[] values) {
    return db.Cars.Where(condition, values);
}

And you set the condition and values outside of the repository: 然后在存储库外部设置条件和值:

string condition = "CarMake == @Make";
object[] values = new string[] { Make = "Ford" };

var result = myRepo.GetCars( condition, values);

How would you be able to sort the result outside of the repository with Dynamic Query? 如何使用Dynamic Query在存储库之外对结果进行排序?

return View( "myView", result.OrderBy("Price"));

Somehow I am losing the DynamicQuery nature when the data exits from the repository. 当数据从存储库退出时,我不知何故失去了DynamicQuery性质。 And yes, I haven't worked out how to return the CarClass type where you would normally do a Select new Carclass { fieldName = m.fieldName, ... } 是的,我还没有找到如何返回通常要执行Select New Carclass的CarClass类型的方法。{fieldName = m.fieldName,...}

Dynamic query requires: 动态查询要求:

  • the source be IQueryable<T> (so if it is IEnumerable<T> or similar, just call .AsQueryable() on it) 源是IQueryable<T> (因此,如果它是IEnumerable<T>或类似的,只需对其调用.AsQueryable()
  • an extra dll to be referenced in the code that wants to perform dynamic query 要执行动态查询的代码中引用的一个额外的dll
  • the appropriate using directives to be in place at the top of the local source file 适当的using指令放在本地源文件的顶部

Check those three, and you should be able to add .Where(condition) , .OrderBy(name) , etc 选中这三个,您应该可以添加.Where(condition) .OrderBy(name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM