开发者

Using dynamic where clauses in Entity Framework

开发者 https://www.devze.com 2023-01-25 04:27 出处:网络
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 t

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 开发者_Python百科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


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();
    }
}


You can use ExecuteStoreQuery method to execute raw commands against the database. http://msdn.microsoft.com/en-us/library/ee358769.aspx


Check out Rick Strahl's blog post here: http://www.west-wind.com/weblog/posts/160237.aspx. His demo uses Linq to SQL but it wouldn't be far different in EF. This approach involves exposing the IQueryable to the business layer. It is not without controversy, but it's something to consider.

With the IQueryable exposed, you can write LINQ queries against the returned collection. I'm not promising that you'll be able to make it work with sprocs, but give it a try.


face same problem,, now the raptier discontinued might be,, well so

i have a clue,, as i am using lite version which support only 15 tables/views.. here is a short cut,,

always take a dummy test db in the server,, and generate the classes which you want, then merge it with your class library solution, rebuild the solution, and move on like that to the extent you want,,

its laborious but its work.

need more help,, with glad...

0

精彩评论

暂无评论...
验证码 换一张
取 消