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

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

问题描述

我正在使用EF 3.5与MVC。



我想做一个搜索页面,有一些字段用于诸如date,int等的标准。



linq中实体过滤结果的方式是什么。



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



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

解决方案

EF 3.5?无论如何...



您可以通过ObjectQuery,ObjectSet或IQueryable追加搜索条件,并根据哪些搜索条件进行链接。

  public SearchMyThings(string a,string b,int c)
{
var mywidgets = ObjectContext.CreateObjectSet< Widget>();
//或EF 1.0版本的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并将其传递。



如果您需要对字符串的更多控制,并且不怕复杂性你可以给 Dynamic Linq a try。


I am using EF 3.5 with MVC.

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

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

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

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

}

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.

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

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

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