ExpressionTree学习笔记

概述:

  这段时间需要制定自定义查询条件,感觉有必要学习ExpressionTree。

  学习参考资料:https://msdn.microsoft.com/en-us/library/mt654263.aspx;https://www.codeproject.com/tips/438804/expression-tree

例子模型:

    public class People
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public int CityID { get; set; }
    }
List<People> people = new List<People>
            {
                new People(){ Name = "Pranay",Email="pranay@test.com",CityID=2 },
                new People(){ Name = "Heamng",Email="Hemang@test.com",CityID=1 },
                new People(){ Name = "Hiral" ,Email="Hiral@test.com",CityID=2},
                new People(){ Name = "Maitri",Email="Maitri@test.com",CityID=1 }
            };

 

完成目标:

  在List<People>中根据Name排序

 实施过程:

问题:

1、如何将已经生成的Expression与分页机制联起来?设想是:将查询条件变成Json格式,在页面端显示string,保存到分页的data属性中,再从后台分解出Json。

目前已成功。

后端生成Json字符串:

ViewBag.searchCondition = JsonConvert.SerializeObject(searchCondition);

 

前端使用Json字符串:

@{
  string jsonSearchCondition = String.Empty;
  if (ViewBag.searchCondition != null)
  {
    jsonSearchCondition = ViewBag.searchCondition;
  }
}

@Ajax.ActionLink(i.ToString(), "Action", "Controller", new { pageIndex = i, pageNumber = ViewBag.pageNumber, jsonSearchCondition = jsonSearchCondition }, new AjaxOptions { UpdateTargetId = "show-list", HttpMethod = "Get", InsertionMode = InsertionMode.Replace })

后端解析Json字符串

SearchDeviceCondition searchCondition = JsonConvert.DeserializeObject<SearchDeviceCondition>(jsonSearchCondition);

 2、And与AndAlso的区别

AndAlso对应"&&"

3、Expression.Equals()相等操作,类型不匹配的问题

var exMaintainInfoID = Expression.Property(Expression.Property(param, "MaintainInfo"), "MaintainInfoID");
                var searchMaintainInfoID =Expression.Convert(Expression.Constant(searchCondition.MaintainInfoID), exMaintainInfoID.Type);
                var equalMaintainInfoID = Expression.Equal(exMaintainInfoID, searchMaintainInfoID);
searchCondition.MaintainInfoID中的类型为int?型,而param=>param.MaintainInfoID类型为int型,直接用Expression.Equals()会提示数据不匹配,无法操作的错误。
解决办法是利用Expression.Convert()将int?型转换成int类型。


4、Enum操作方法

4.1需要用到EnumType本身

 Expression searchMaintainResult = Expression.Constant( searchCondition.MaintainResult, typeof(MaintainResultEnum));
                Expression exMaintainResult = Expression.Property(param, "MaintainResult");
                Expression equalMaintainResult = Expression.Equal(exMaintainResult, searchMaintainResult);

利用Expression.Constant(, Type)中的第二个参数Type,将该值设为EnumType.

4.2需要用到EnumType中的值

var maintainLevel = (int)searchCondition.RadioMaintainLevel;
                Expression searchMaintainLevel = Expression.Constant(maintainLevel);
 exMaintainLevel = Expression.Property(exMaintainLevel, "MaintainLevelClass");
                Expression equalMaintainLevel = Expression.Equal(exMaintainLevel, searchMaintainLevel);

比如EnumType中的项设为int=1,需要用到“1”的值,先转换成int型。

posted @ 2017-02-21 11:53  哈哈兮  阅读(369)  评论(0编辑  收藏  举报