您的位置:首页 > 产品设计 > UI/UE

wcf ria 解决linq表达式拼接动态查询的类PredicateBuilder

2011-12-21 11:05 519 查看
解决linq表达式拼接动态查询的类PredicateBuilder

在domain service 的客户端调用时应用

public static class PredicateBuilder
{
/// <summary>
/// 机关函数应用True时:单个AND有效,多个AND有效;单个OR无效,多个OR无效;混应时写在AND后的OR有效
/// 机关函数应用False时:单个AND无效,多个AND无效;单个OR有效,多个OR有效;混应时写在OR后面的AND有效
/// </summary>
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }

public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
}

public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
}

public static Predicate<T> ConvertToPredicate<T>(this Func<T, bool> func)
{
return new Predicate<T>(func);
}
}
社会主义制度的建立给我们开辟了一条到达理想境界的道路,而理想境界的实现还要靠我们的辛勤劳动。——毛泽东

终于解决了Linq动态、多条件在EF、RIA、DS里面的用法,整理了相关参考地址。

 

PredicateBuilder(Expressions扩展)
http://www.albahari.com/nutshell/linqkit.aspx
System.Linq.Dynamic (Dynamic.cs)扩展类

可以在VS自带demo里找到。

(VS2010目录C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\2052\CSharpSamples.zip-CSharpSamples\LinqSamples\DynamicQuery)

 

相关

动态模糊查询
http://stackoverflow.com/questions/4599989/how-dynamic-library-system-linq-dynamic-support-like-operator
动态查询语法
http://www.beansoftware.com/ASP.NET-Tutorials/Dynamic-LINQ.aspx
动态创建在WCF RIA Services
http://weblogs.asp.net/fredriknormen/archive/2009/12/30/wcf-ria-services-dynamically-create-a-criteria-on-the-client-side.aspx
 

其他

Writing Dynamic Linq Queries in Linq-to-Entities
http://naspinski.net/post/Writing-Dynamic-Linq-Queries-in-Linq-to-Entities.aspx
LINQ – LINQKit(PredicateBuilder)
http://www.dotblogs.com.tw/alonstar/archive/2010/06/30/16274.aspx
Expression<Func<T, bool>>相关,这东西我还没玩转,在DomainServices里不好使。

Building LINQ Queries at Runtime in C#
http://tomasp.net/blog/dynamic-linq-queries.aspx
linq to sql 多条件组合查询
http://www.cnblogs.com/ChaosHero/archive/2010/06/20/1761444.html
Linq动态查询与模糊查询(带源码示例)
http://www.cnblogs.com/killuakun/archive/2008/08/03/1259389.html 他用的PredicateBuilder,思路清晰,简单。
LINQ体验(17)——LINQ to SQL语句之动态查询
http://www.cnblogs.com/lyj/archive/2008/03/25/1122157.html
Linq To Sql进阶系列(六)用object的动态查询与保存log篇
http://www.cnblogs.com/126/archive/2007/09/09/887723.html
浅谈Linq To Sql集成数据库语言的优劣
http://www.bccn.net/Article/sjk/sqlserver/jszl/200709/6578.html
 

贴个例子,基本解决了string、int、datetime、bool类型的拼接方法,特别注意下如果拼成一条string的格式写法,用参数传递格式就不太重要了

 

MVVM-ViewModels

private LoadOperation<V_Store> LoadSampleEntities()
{
this.CanLoad = false;

string strWhere = " 1=1";
if (!string.IsNullOrWhiteSpace(Tt_Company)) strWhere += " and co_Company.Contains(\"" + Tt_Company + "\")";
if (!string.IsNullOrWhiteSpace(Tt_Name)) strWhere += " and co_Name.Contains(\"" + Tt_Name + "\")";
if (!string.IsNullOrWhiteSpace(Tt_MPa)) strWhere += " and co_MPa.Contains(\"" + Tt_MPa + "\")";
if (!string.IsNullOrWhiteSpace(Tt_Spec)) strWhere += " and co_Spec.Contains(\"" + Tt_Spec + "\")";
if (!string.IsNullOrWhiteSpace(Tt_Mill)) strWhere += " and co_Mill.Contains(\"" + Tt_Mill + "\")";
if (!string.IsNullOrWhiteSpace(Tt_Remark)) strWhere += " and co_Remark.Contains(\"" + Tt_Remark + "\")";
if (!string.IsNullOrWhiteSpace(Tt_StartAmount) && Utils.IsNumeric(Tt_StartAmount))
{//数量
Decimal SAmount = Decimal.Parse(Tt_StartAmount);
strWhere += " and co_Amount >= " + SAmount;
}
if (!string.IsNullOrWhiteSpace(Tt_EndAmount) && Utils.IsNumeric(Tt_EndAmount))
{
Decimal EAmount = Decimal.Parse(Tt_EndAmount);
strWhere += " and co_Amount <= " + EAmount;
}
if (!string.IsNullOrWhiteSpace(Tt_StartWeight) && Utils.IsNumeric(Tt_StartWeight))
{//重量
Decimal SWeight = Decimal.Parse(Tt_StartWeight);
strWhere += " and co_Weight >= " + SWeight;
}
if (!string.IsNullOrWhiteSpace(Tt_EndWeight) && Utils.IsNumeric(Tt_EndWeight))
{
Decimal EWeight = Decimal.Parse(Tt_EndWeight);
strWhere += " and co_Weight <= " + EWeight;
}
if (!string.IsNullOrWhiteSpace(Dt_StartTime))
{//时间
DateTime STime = DateTime.Parse(Dt_StartTime);
string STimeFormat = STime.ToString("yyyy,MM,dd");
strWhere += " and co_UpDateTime >= DateTime(" + STimeFormat + ")";
}
if (!string.IsNullOrWhiteSpace(Dt_EndTime))
{
DateTime ETime = DateTime.Parse(Dt_EndTime).AddDays(1);
string ETimeFormat = ETime.ToString("yyyy,MM,dd");
strWhere += " and co_UpDateTime <= DateTime(" + ETimeFormat + ")";
}
if (Ci_IsZero) strWhere += " and co_Amount != 0 and co_Weight != 0";

//截入条件,返回一个查询后的Sum结果。
InvokeOperation<decimal> invokeOperation = ds.GetV_StoreWeightSum(strWhere, OnInvokeCallback, null);

//载入了相同的条件,查询后返回记录。
return ds.Load(ds.GetV_StoreWhereQuery(strWhere).SortAndPageBy(_view));
}

DomainService

public IQueryable<V_Store> GetV_StoreWhere(string strWhere)
{
return ObjectContext.V_Store.Where(strWhere, new object[] { }).OrderByDescending(e => e.co_StoreID);
}

[Invoke]
public decimal GetV_StoreWeightSum(string strWhere)
{
return ObjectContext.V_Store.Where(strWhere, new object[] { }).Sum(e => e.co_Weight);
}


复制代码
 

解决linq表达式拼接动态查询的类PredicateBuilder

在domain service 的客户端调用时使用

public static class PredicateBuilder

    {

        /// <summary>

        /// 构造函数使用True时:单个AND有效,多个AND有效;单个OR无效,多个OR无效;混合时写在AND后的OR有效

        /// 构造函数使用False时:单个AND无效,多个AND无效;单个OR有效,多个OR有效;混合时写在OR后面的AND有效

        /// </summary>

        public static Expression<Func<T, bool>> True<T>() { return f => true; }

        public static Expression<Func<T, bool>> False<T>() { return f => false; }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,

                                                            Expression<Func<T, bool>> expr2)

        {

            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());

            return Expression.Lambda<Func<T, bool>>

                  (Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);

        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,

                                                             Expression<Func<T, bool>> expr2)

        {

            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());

            return Expression.Lambda<Func<T, bool>>

                  (Expression.And(expr1.Body, invokedExpr), expr1.Parameters);

        }

        public static Predicate<T> ConvertToPredicate<T>(this Func<T, bool> func)

        {

            return new Predicate<T>(func);

        }

    }

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: