Linq with EF dynamic search

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I am using EF 3.5 with MVC.

I want to made a search page, has some fields for criteria like date, int etc.

What is the way in linq to entities to filter the result dynamically.

If there are one parameter we can use .where(a=>a.id==1)

but many combination with optional param how can i load results and then pass to model.

回答1:

EF 3.5? Anyway...

You can append search criteria over an ObjectQuery, ObjectSet or IQueryable and chain them based on which search criteria is useful.

public SearchMyThings( string a, string b, int c ) {      var mywidgets = ObjectContext.CreateObjectSet<Widget>();      //or the EF 1.0 version CreateSet?       if( !a.IsNullOrEmpty )         mywidgets = mywidgets.Where( w => w.AProperty == a );       if( !b.IsNullOrEmpty )         mywidgets = mywidgets.Where( w => w.BProperty == b );       if( c > 0 )         mywidgets = mywidgets.Where( c => c.CProperty == c );  } 

If you need a string based approach you can always use the overloads of ObjectQuery.Where("esql") to dynamically construct some eql and passing that along.

If you need MORE control over the strings and aren't afraid of complexity you could give Dynamic Linq a try.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!