Click here to Skip to main content
15,178,226 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I Search a lot but i can not find answer.
how can create a query in entity framework that get all record of table with some condition.
i want to this query have some parameter that can be null.
parameter:string name,int id
these parameter can have value or null.
if name parameter is null,dont use this condition.
how can do it?
thank you in advance
George Swan 2-Aug-15 11:37am
Can't you just check for null in your 'Where' clause?
Where(u=>user.Name!=null && u.Name.Contains(user.Name) && user.ID!=null && u.ID==user.ID)

I would suggest going through some tutorials. For example:
- Querying with EDM:[^]
- Queries in LINQ to Entities[^]

Depending on the query technology you choose, the condition is expressed differently. Beyond that it would be helpful to have a data example explaining what you're after.
user12213212 1-Aug-15 23:15pm
thanks.but i can not find answer.
i create this method:
public List<user> SearchUsers(Users user)
List<user> lstUser;
using (var ctx = new MyEntities())
result = ctx.User
.Where(u=>u.Name.Contains(user.Name)) && u=>u.ID==user.ID)))
.OrderByDescending(u => u.ID)
return result;
when i call it,should, user.ID have value,but i want to be null sometimes.ID is int , name is string(30).i read them from textbox.
how to create and call this method?
Wendelius 2-Aug-15 0:13am
One easy way is to do the query in parts. First use the static conditions to get the results and then based on input from the user run new queries based on the previous query. In pseudo code

var startquery = from i in list
where some static condition
select i;

if (!string.IsNullOrEmpty(user.Name) {
var result = from i in startquery
where i.Name.Contains(user.Name)
select i;
one way is:
public List<User> SearchUsers(string userName, int? userId)
    using (var ctx = new MyEntities())
        IQueryable<User> query = ctx.User;

        if (userName != null)
            query = query.Where(u=>u.Name.Contains(userName));

        if (userId != null)
            query = query.Where(u=>u.ID==userId.Value);

        var users = query
            .OrderByDescending(u => u.ID)

        return users;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900