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.Contain开发者_开发知识库s(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 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 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 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.
精彩评论