LINQ与EF动态搜索 [英] Linq with EF dynamic search

查看:250
本文介绍了LINQ与EF动态搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EF 3.5 MVC。

I am using EF 3.5 with MVC.

我要提出一个搜索页面,对喜欢日期条件某些领域,诠释等等。

I want to made a search page, has some fields for criteria like date, int etc.

什么是LINQ到实体的方式动态地过滤结果。

What is the way in linq to entities to filter the result dynamically.

如果有一个参数,我们可以使用
。凡(一个=> a.id == 1)

If there are one parameter we can use .where(a=>a.id==1)

但可选的参数我如何可以加载结果,然后传递给模型。许多组合

but many combination with optional param how can i load results and then pass to model.

推荐答案

EF 3.5?反正...

EF 3.5? Anyway...

您可以附加搜索条件了一个多的ObjectQuery,对象集或IQueryable的,并在此基础上的搜索条件是非常有用的连锁它们。

You can append search criteria over an ObjectQuery, ObjectSet or IQueryable and chain them based on which search criteria is useful.

public SearchMyThings( string a, string b, int c )
{
     var mywidgets = ObjectContext.CreateObjectSet<Widget>();
     //or the EF 1.0 version CreateSet?

     if( !a.IsNullOrEmpty )
        mywidgets = mywidgets.Where( w => w.AProperty == a );

     if( !b.IsNullOrEmpty )
        mywidgets = mywidgets.Where( w => w.BProperty == b );

     if( c > 0 )
        mywidgets = mywidgets.Where( c => c.CProperty == c );

}

如果你需要一个基于字符串的方法,您可以随时使用ObjectQuery.Where(ESQL)的重载动态构造一些EQL和传球沿。

If you need a string based approach you can always use the overloads of ObjectQuery.Where("esql") to dynamically construct some eql and passing that along.

如果您需要在字符串的更多控制和不怕复杂,你可以给<一个href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx\"相对=nofollow>动态的LINQ 的一个尝试。

If you need MORE control over the strings and aren't afraid of complexity you could give Dynamic Linq a try.

这篇关于LINQ与EF动态搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆