views:

185

answers:

1

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.

A: 

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.

jfar