Search page with MVC + Linq + EF

2020-07-14 05:17发布

问题:

So, I want to implement a page that searches the database for records. The url of the action should be something like "~/Mail/List/{PropertyName}/{PropertyValue}.

Property name and value are the corresponding entity property name to filter by and the value is the property value to match. The thing is that the entity contains properties of many types. Int, string, date.. etc.

The question is, how do I implement a dynamic search page or something like that to filter my queries?

Thanks!

回答1:

All LINQ operators expects lambdas to be passed in. So when you want to do filtering like Where(x => x.[PropertyName] == [PropertyValue]), you need to be able to construct the corresponding lambda expression. Normally, when values are known at compile time, there's no problem, you'll just construct the lambda.

When you don't know the values at compile time, you have to construct expression tree (that is essentially what lambda expression is made of) manually. This can be a bit complicated, but there are libraries to help you, like Dynamic LINQ (here is another good tutorial with EF). You can then specify your Where condition as a string and the library at runtime will translate it into expression tree or throw an exception if it is wrong.

So, in your example, using Dynamic LINQ, you can do your query like db.Mails.Where(PropertyName + " == @0", PropertyValue);