Using dynamic where clauses in Entity Framework

不打扰是莪最后的温柔 提交于 2019-12-01 09:04:32

问题


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


回答1:


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



回答2:


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




回答3:


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.




回答4:


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...



来源:https://stackoverflow.com/questions/4198318/using-dynamic-where-clauses-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!