none
Dynamic Query in Entity Framework RRS feed

  • General discussion

  • Hi,

    I am in need of creating an Generic function which could do dynamic Filtering, Sorting, Paging concepts. How could that be achieved using EF 6.0?

    For example I have an entity "Customer" which has 3 Columns viz FirstName, LastName and isActive. I am not interested in writing a query like

     using (var context = new MyContext())
        {
            var predicate = PredicateBuilder.True<Customer>();
            if (!string.IsNullOrWhiteSpace(searchCriteria.FirstName))
            {
                predicate = predicate.And(x => x.firstName.Contains(searchCriteria.FirstName));
            }
            if (!string.IsNullOrWhiteSpace(searchCriteria.LastName))
            {
                predicate = predicate.And(x => x.lastName.Contains(searchCriteria.LastName));
            }
            if (searchCriteria.IsActive != null)
            {
                predicate = predicate.And(x => x.isActive == searchCriteria.IsActive);
            }

    How should I write a dynamic query which does filter criteria?

    Regards,

    Raghul



    Thursday, September 18, 2014 4:50 PM

All replies

  • I am in need of creating an Generic function which could do dynamic Filtering, Sorting, Paging concepts. How could that be achieved using EF 6.0?

    I don't think I would be bothered with anything using Linq. I would go with dynamic Entity-SQL to build dynamic queries, like it would be done if using dynamic T-SQL.  I have used the PredicateBuilder, and it just never worked out for me when doing complicated dynamic Linq queries.

    Entity-SQL is much more flexable and dynamic.

    Thursday, September 18, 2014 6:24 PM
  • Hello Raghul,

    >>How should I write a dynamic query which does filter criteria?

    You could also consider using the LINQ Dynamic Query Library:

    http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library

    Regards,

    Fred.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, September 19, 2014 1:40 AM
    Moderator