简体   繁体   中英

Linq with EF dynamic search

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.

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.

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