简体   繁体   中英

dynamic where clause entity framework 3.5

I am new to entity framework. I need to develop a Linq query based on Orders and Customers.

for eg: string firstName can have any of the three values

1) null 2) Joe 3) like %Joe%'

simailary i need to develop for lastname

My current query is like this

                using (NorthwindEntities ent = new NorthwindEntities())
                {
                    var UsersList = ent.User.Include("Orders").
                                Include("OrderDetails").
                                Include("OrderDetails.Products").
                               .Where(o => (firstName== null || o.firstName== firstName||o.firstName.Contains(firstName)) 
&& (LastName== null || o.LastName== LastName ||o.LastName.contains(LastName) ) 

    }

Is my query is correct. Is any other better option to write linq entity query.

Thanks

you can split your query in parts, its somewhat nicer then:

var UsersList = ent.User.Include("Orders")
                        .Include("OrderDetails")
                        .Include("OrderDetails.Products");

if(!string.IsNullOrEmpty(firstName));
   UsersList = UsersList.Where( o => o.firstName.Contains(firstName));

if(!string.IsNullOrEmpty(lastName));
   UsersList = UsersList.Where( o => o.lastName.Contains(lastName))

Also the check o.firstName == firstName is redundant, the Contains(firstName) part is sufficient (same for lastName).

You can add conditions to a Queryable object. The conditions will build up until the data query is executed.

var UsersList = ent.User.Include("Orders")
               .Include("OrderDetails")
               .Include("OrderDetails.Products");

if (!string.IsNullOrEmpty(firstName))
   UsersList = UsersList.Where( o => o.firstName.Contains(firstName));

if (!string.IsNullOrEmpty(LastName))
   UsersList = UsersList.Where( o => o.LastName.Contains(LastName));

You could build up your query in steps:

    using (NorthwindEntities ent = new NorthwindEntities())
    {
       var UsersList = ent.User.Include("Orders")
                .Include("OrderDetails")
                .Include("OrderDetails.Products");
       if (LastName != null)
          UserList = UserList.Where(o => o.LastName == LastName || o.LastName.contains(LastName));

       if (FirstName != null)
          UserList = UserList.Where(o => o.firstName== firstName||o.firstName.Contains(firstName);

       // etc
   }

The query won't execute until you do a ToList() or use it in a foreach or something like that.

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