user122121212
user122121212

Reputation: 40

create query with parameter that can be null

I create this method:

public List SearchUsers(Users user)
{
    List 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)
            .ToList();
        return lstUser;
    }
}

When I call it, should user.name, user.ID parameters 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?

Upvotes: 0

Views: 125

Answers (1)

Will
Will

Reputation: 2532

Something like this might do the trick: Either fill userName and userId when calling the method, or leave one or both null as suits to disable that part of the search.

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)
            .ToList();

        return users;
    }
}

Upvotes: 2

Related Questions