开发者

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

开发者 https://www.devze.com 2022-12-23 16:12 出处:网络
If you do something like this in your Repository: IQueryable<CarClass> GetCars(string condition, params object[] values) {

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 str开发者_如何学Cing[] { Make = "Ford" };

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

How would you be able to sort the result outside of the repository with Dynamic Query?

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

Somehow I am losing the DynamicQuery nature when the data exits from the repository. 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, ... }


Dynamic query requires:

  • the source be IQueryable<T> (so if it is IEnumerable<T> or similar, just call .AsQueryable() on it)
  • an extra dll to be referenced in the code that wants to perform dynamic query
  • the appropriate using directives to be in place at the top of the local source file

Check those three, and you should be able to add .Where(condition), .OrderBy(name), etc

0

精彩评论

暂无评论...
验证码 换一张
取 消