Using dynamic where clauses in Entity Framework

痴心易碎 提交于 2019-12-01 09:35:16

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

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