Search code examples
c#entity-frameworkdata-access-layer

Using dynamic where clauses in Entity Framework


I am trying to re-design a data access layer that was originally built using Raptier. Raptier generats methods that accept a where clause as a parameter to be passed in to a stored proc. I really need to retain the existing mesthos signatures, so my new DAL needs to accept where clauses as well. I want to use the more up-to-date data access technologies and techniques, so was thinking about using Entity Framework from .Net 4.0.

However, it doesn't look like I can accept dynamic where clauses without implementing some intense reoutines to parse them into lamba expressions. Is there something I've missed? Am I out of luck with Entity Framework?

Thanks, Marc


Solution

  • Two ideas come in mind.

    1). Dynamic LINQ, which allows you to define where operators as strings.

    var result = Northwind.Products
        .Where("CategoryId=2 And UnitPrice>3")
        .OrderBy("SupplierId");
    

    2). Use something as the EntityFilter<T> (see code here), which allows you to define a filter like this:

    IEntityFilter<Person> entityFilter =
        from person in EntityFilter<Person>.AsQueryable()
        where person.Name.StartsWith("a")
        where person.Id < 100
        select person;
    

    You can supply the IEntityFilter<Person> to a business method that will be able to filter that query:

    public static Person[] GetAllPersons(
        IEntityFilter<Person> filter)
    {
        using (var db = ContextFactory.CreateContext())
        {
            IQueryable<Person> filteredList =
                filter.Filter(db.Persons);
    
            return filteredList.ToArray();
        }
    }