简体   繁体   中英

Search page with MVC + Linq + EF

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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