您的位置:知识库 » 数据库

Linq To Sql进阶系列(七)动态查询续及CLR与SQL在某些细节上的差别

作者: Tom Song  来源: 博客园  发布时间: 2008-09-27 12:04  阅读: 16996 次  推荐: 0   原文链接   [收藏]  

系列文章导航:

Linq To Sql进阶系列(一)从映射讲起

Linq To Sql进阶系列(二)M:M关系

Linq To Sql进阶系列(三)CUD和Log

Linq To Sql进阶系列(四)User Define Function篇

Linq To Sql进阶系列(五)Store Procedure篇

Linq To Sql进阶系列(六)用object的动态查询与保存log篇

Linq To Sql进阶系列(七)动态查询续及CLR与SQL在某些细节上的差别



2,限定字段在某集合中
这有点像in操作。比如where city in ('London', 'BeiJing') 也可以写成 where city = 'London' or city = 'BeiJing'。既然谈到or条件的动态构造了,那就也来构造下这个吧。看上去有点多此一举。但是,至少是个很好的学习机会。这个和上面不同的是,它条件字段是唯一的,变化的是该字段的值。那用一string将字段名成传入,并用一集合将字段值传入函数。
该函数完整的定义入下:


    
public static IQueryable<TEntity> WhereOr<TEntity, OrType>(this IQueryable<TEntity> source,
string
 propertyName, IEnumerable<OrType> values)
    
{
        
if (source == null)
            
throw new ArgumentNullException("Source can't be null!!");
        ParameterExpression param 
= Expression.Parameter(typeof(TEntity), "p");
        Expression left 
= Expression.Property(param, propertyName);
        Expression condition 
= null;
        
foreach (OrType value in values)
        
{
            Expression filter 
= Expression.Equal(left, Expression.Constant(value));
            
if (condition == null)
                condition 
= filter;
            
else
                condition 
= Expression.Or(condition,filter);
        }

        
if (condition != null)
            
return source.Where((Expression<Func<TEntity, bool>>)Expression.Lambda(condition,
param));

        
return source;
    }


使用时,
       var q3 = db.Customers.WhereOr("City", new List<string> { "London", "BeiJing" }).ToList();
并不在多做解释。

0
0
 

数据库热门文章

    数据库最新文章

      最新新闻

        热门新闻