1

I create a few filters, which can be used by user. So user can send me a value in it or can. How can I check if user send me a value or only null? Now I check it like this, it´s working, but this isn´t ideal solution:

public ActionResult Index(int? SearchStuff, int? SearchCustomer, int? SearchWorker, int? SearchOrder, String SearchDate)
    {
        var stuff = from s in db.Orders select s;
        var customer = from c in db.Orders select c;
        var worker = from w in db.Orders select w;
        var order = from o in db.Orders select o;
        var date = from d in db.Orders select d;
        var helper = from d in db.Orders select d;
        IQueryable<Order> filter = order;

       if (SearchCustomer != null && !String.IsNullOrEmpty(SearchDate) && SearchStuff != null && SearchWorker != null)
        {
            helper = helper.Where(a => a.CustomerId == SearchCustomer).Where(a => a.StuffId == SearchStuff).Where(a => a.WorkerId == SearchWorker).Where(a => a.Date.Contains(SearchDate));
            filter= helper;
        }
0

2 Answers 2

1

You could try something like this, I see it often used in stored procedures as well (I added the first three search options but you can add as many as you like):

    Public ActionResult Index(int? searchStuff, int? searchCustomer, int? searchWorker)
    {
        myOrders = db.Orders
            .Where(o => (searchStuff == null || o.StuffId == searchStuff)
                     && (searchCustomer == null || o.CustomerId == searchCustomer)
                     && (searchWorker == null || o.WorkerId == searchWorker));
    }
Sign up to request clarification or add additional context in comments.

Comments

0

I did the following:

var stuff = db.Orders.AsQueryable();
if(searchStuff.HasValue)
{
    stuff = stuff.Where(x=>x.stuffId == searchStuff.Value);
}
if(searchCustomer.hasValue)
{
    stuff = stuff.Where(x=>x.CustomerId == searchCustomer.Value);
}

And so on. With this approach you can do more complex filters like e.g. date ranges.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.