locked
search query with optional fields in entity framework? RRS feed

  • Question

  • User943281425 posted

    I have created a model with search parameter in  MVC 5 application

    Chances are that all the parameter could be null or few could be null.

    Now how to create dynamic query for the search based on the values of property in Entity Framework 6?

    thanks in advance.

    Wednesday, October 15, 2014 7:43 AM

Answers

  • User1918509225 posted

    Hi abhi0410,

    Just like Mikesdotnetting suggestion,you need to build your LINQ statement dynamically.

    It seems that you can't create a query and entity framework ignore if the paramter is null.

    Best Regards,

    Kevin Shen.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 16, 2014 1:46 AM

All replies

  • User-821857111 posted

    One option is to build your LINQ statement dynamically:

    var data = context.Students;
    if(lastname != null){
        data = data.Where(s => s.LastName == lastname);
    }
    if(mobile != null){
        data = data.Where(s => c.Mobile == mobile);
    }

    You can read more about it here: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

    Wednesday, October 15, 2014 8:09 AM
  • User943281425 posted

    Hi Mike,

    In your case i am checking property one by one then creating the query.

    Then i have to make many Permutation and Combination to build query.

    We don't have any option in EF where we create a simply query with all parameter and ask EF to ignore if the parameter is NULL?

    Just a guess.

    Thanks.

    Wednesday, October 15, 2014 8:34 AM
  • User1918509225 posted

    Hi abhi0410,

    Just like Mikesdotnetting suggestion,you need to build your LINQ statement dynamically.

    It seems that you can't create a query and entity framework ignore if the paramter is null.

    Best Regards,

    Kevin Shen.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 16, 2014 1:46 AM