首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >一句代码实现批量数据绑定[下篇]

一句代码实现批量数据绑定[下篇]

作者头像
蒋金楠
发布2018-02-08 15:20:48
7220
发布2018-02-08 15:20:48
举报
文章被收录于专栏:大内老A大内老A大内老A

上篇》主要介绍如何通过DataBinder实现批量的数据绑定,以及如何解决常见的数据绑定问题,比如数据的格式化。接下来,我们主要来谈谈DataBinder的设计,看看它是如何做到将作为数据源实体的属性值绑定到界面对应的控件上的。此外,需要特别说明一点:《上篇》中提供了DataBinder最初版本的下载,但已经和本篇文章介绍的已经大不一样了。最新版本的主要解决两个主要问题:通过Expression Tree的方式进行属性操作(属性赋值和取值),添加了“数据捕捉”(Data Capture)的功能,以实现将控件中的值赋给指定的实体。但是,这并不意味着这就是一个最终版本,这里面依然有一些问题,比如对空值的处理不不够全面,比如在进行数据绑定的时候,有的控件类型需要进行HTML Encoding,等等。[源代码从这里下载]

目录: 一、通过DataPropertyAttribute特性过滤实体的“数据属性” 二、Control/DataSource映射的表示:BindingMapping 三、如何建立Control/DataSource映射集合 四、通过映射集合实现数据绑定 五、通过映射集合实现数据捕捉

一、通过DataPropertyAttribute特性过滤实体的数据属性

DataBinder在进行数据绑定的时候,并没有对作为数据源的对象作任何限制,也就是说任何类型的对象均可作为数据绑定的数据源。控件(这里指TextBox、Label等这样绑定标量数值的控件)绑定值来源于数据源实体的某个属性。但是一个类型的属性可能有很多,我们需要某种筛选机制将我们需要的“数据属性”提取出来。这里我们是通过在属性上应用DataPropertyAttribute一个特性来实现的。

简单起见,我不曾为DataPropertyAttribute定义任何属性成员。DataPropertyAttribute中定义了一个静态的GetDataProperties方法,得到给定实体类型的所有数据属性的名称。但是为了避免频繁地对相同实体类型进行反射,该方法对得到的属性名称数组进行了缓存。

   1: [AttributeUsage( AttributeTargets.Property, AllowMultiple = false,Inherited = true)]
   2: public class DataPropertyAttribute: Attribute
   3: {
   4:     private static Dictionary<Type, string[]> dataProperties = new Dictionary<Type, string[]>();
   5:     public static string[] GetDataProperties(Type entityType)
   6:     {
   7:         Guard.ArgumentNotNullOrEmpty(entityType, "entityType");
   8:         if (dataProperties.ContainsKey(entityType))
   9:         {
  10:             return dataProperties[entityType];
  11:         }
  12:         lock (typeof(DataPropertyAttribute))
  13:         {
  14:             if (dataProperties.ContainsKey(entityType))
  15:             {
  16:                 return dataProperties[entityType];
  17:             }
  18:             var properties = (from property in entityType.GetProperties()
  19:                               where property.GetCustomAttributes(typeof(DataPropertyAttribute), true).Any()
  20:                               select property.Name).ToArray();
  21:             dataProperties[entityType] = properties;
  22:             return properties;
  23:         }
  24:     }
  25: }

二、Control/DataSource映射的表示:BindingMapping

不论是数据绑定(实体=〉控件),还是数据捕捉(控件=〉实体)的实现都建立在两种之间存在着某种约定的映射之上,这个映射是整个DataBinder的核心所在。在这里,我定义了如下一个BindingMapping类型表示这个映射关系。

   1: public class BindingMapping: ICloneable
   2: {
   3:     public Type DataSourceType { get; private set; }
   4:     public Control Control { get; set; }
   5:     public string ControlValueProperty { get; set; }
   6:     public string DataSourceProperty { get; set; }
   7:     public bool AutomaticBind { get; set; }
   8:     public bool AutomaticUpdate { get; set; }
   9:     public string FormatString { get; set; }
  10:     public Type ControlValuePropertyType
  11:     {
  12:         get { return PropertyAccessor.GetPropertyType(this.Control.GetType(), this.ControlValueProperty); }
  13:     }
  14:     public Type DataSourcePropertyType
  15:     {
  16:         get { return PropertyAccessor.GetPropertyType(this.DataSourceType, this.DataSourceProperty); }
  17:     }
  18:  
  19:     public BindingMapping(Type dataSourceType, Control control, string controlValueProperty, string dataSourceProperty)
  20:     {
  21:          //...
  22:         this.DataSourceType         = dataSourceType;
  23:         this.Control                = control;
  24:         this.ControlValueProperty   = controlValueProperty;
  25:         this.DataSourceProperty     = dataSourceProperty;
  26:         this.AutomaticBind          = true;
  27:         this.AutomaticUpdate        = true;
  28:     }
  29:     object ICloneable.Clone()
  30:     {
  31:         return this.Clone();
  32:     }
  33:     public BindingMapping Clone()
  34:     {
  35:         var bindingMapping = new BindingMapping(this.DataSourceType, this.Control, this.ControlValueProperty, this.DataSourceProperty);
  36:         bindingMapping.AutomaticBind = this.AutomaticBind;
  37:         bindingMapping.AutomaticUpdate = this.AutomaticBind;
  38:         return bindingMapping;
  39:     }
  40: }

这里我主要介绍一下各个属性的含义:

  • DataSourceType:作为数据源实体的类型;
  • Control:需要绑定的控件;
  • ControlValueProperty:数据需要绑定到控件属性的名称,比如TextBox是Text属性,而RadioButtonList则是SelectedValue属性;
  • DataSourceProperty:实体类型中的数据属性名称
  • AutomaticBind:是否需要进行自动绑定,通过它阻止不必要的自动数据绑定行为。默认值为True,如果改成False,基于该条映射的绑定将被忽略;
  • AutomaticUpdate:是否需要进行自动更新到数据实体中,通过它阻止不必要的自动数据捕捉行为。默认值为True,如果改成False,基于该条映射的数据捕捉定将被忽略;
  • FormatString:格式化字符串;
  • ControlValuePropertyType:控件绑定属性的类型,比如TextBox的绑定属性为Text,那么ControlValuePropertyType为System.String;
  • DataSourcePropertyType:实体属性类型。

需要补充一点的是:ControlValuePropertyType和DataSourcePropertyType使用到了之前定义的用于操作操作属性的组件ProcessAccessor。BindingMapping采用了克隆模式。

三、如何建立Control/DataSource映射集合

BindingMapping表示的一个实体类型的数据属性和具体控件之间的映射关系,而这种关系在使用过程中是以批量的方式进行创建的。具体来说,我们通过指定实体类型和一个作为容器的空间,如果容器中的存在满足映射规则的子控件,相应的映射会被创建。映射的批量创建是通过DataBinder的静态方法BuildBindingMappings来实现的。

在具体介绍BuildBindingMappings方法之前,我们需要先来讨论一个相关的话题:在进行数据绑定的时候,如何决定数据应该赋值给控件的那个属性。我们知道,不同的控件类型拥有不同的数据绑定属性,比如TextBox自然是Text属性,CheckBox则是Checked属性。ASP.NET在定义控件类型的时候,采用了一个特殊性的特性ControlValuePropertyAttribute来表示那个属性表示的是控件的“值”。比如TextBox和CheckBox分别是这样定义的。

   1: [ControlValueProperty("Text")]
   2: public class TextBox : WebControl, IPostBackDataHandler, IEditableTextControl, ITextControl
   3: {
   4:     //...
   5: }
   6:  
   7: ControlValueProperty("Checked")]
   8: public class CheckBox : WebControl, IPostBackDataHandler, ICheckBoxControl
   9: {
  10:     //...
  11: }

在这里我们直接将ControlValuePropertyAttribute中指定的名称作为控件绑定的属性名,即BindingMapping的ControlValueProperty属性。该值得获取通过如下一个GetControlValuePropertyName私有方法完成。为了避免重复反射操作,这里采用了全局缓存。

   1: private static string GetControlValuePropertyName(Control control)
   2: {
   3:     if (null == control)
   4:     {
   5:         return null;
   6:     }
   7:     Type entityType = control.GetType();
   8:     if (controlValueProperties.ContainsKey(entityType))
   9:     {
  10:         return controlValueProperties[entityType];
  11:     }
  12:     lock (typeof(DataBinder))
  13:     {
  14:         if (controlValueProperties.ContainsKey(entityType))
  15:         {
  16:             return controlValueProperties[entityType];
  17:         }
  18:         ControlValuePropertyAttribute controlValuePropertyAttribute = (ControlValuePropertyAttribute)entityType.GetCustomAttributes(typeof(ControlValuePropertyAttribute), true)[0];
  19:         controlValueProperties[entityType] = controlValuePropertyAttribute.Name;
  20:         return controlValuePropertyAttribute.Name;
  21:     }
  22: }

最终的映射通过如下定义的BuildBindingMappings方法来建立,缺省参数suffix代表的是控件的后缀,其中已经在《上篇》介绍过了。

   1: public static IEnumerable<BindingMapping> BuildBindingMappings(Type entityType, Control container, string suffix = "")
   2: {
   3:     //...
   4:     suffix = suffix??string.Empty;
   5:     return (from property in DataPropertyAttribute.GetDataProperties(entityType)
   6:             let control = container.FindControl(string.Format("{1}{0}", suffix, property))
   7:             let controlValueProperty = GetControlValuePropertyName(control)
   8:             where null != control
   9:             select new BindingMapping(entityType, control, controlValueProperty, property)).ToArray();
  10: }

四、通过映射集合实现数据绑定

通过《上篇》我们知道,DataBinder提供两种数据绑定方式:一种是直接通过传入数据实体对象和容器控件对具有匹配关系的所有子控件进行绑定;另外一种则是通过调用上面BuildBindingMappings静态方法建立的BindingMapping集合,然后再借助于这个集合进行数据绑定。这两种方式的数据绑定对应于如下两个重载的BindData方法:

   1: public class DataBinder
   2: { 
   3:     //...
   4:     public void BindData(object entity, Control container, string suffix = "");
   5:     public void BindData(object entity,IEnumerable<BindingMapping> bindingMappings);
   6: }

已经上在内部,上面一个方法也是需要通过调用BuildBindingMappings来建立映射。数据绑定始终是根据BindingMapping集合进行的。由于在BindingMapping中已经定义了完成数据绑定所需的必要信息,数据绑定的逻辑变得很简单。具体来说,数据绑定的逻辑是这样的:遍历所有的集合中每个BindingMapping,根据DataSourceProperty得到属性名称,然后进一步从数据源实体中得到具体的值。根据ControlValuePropertyType得到目标控件绑定属性的类型,然后将之前得到的值转换成该类型。最后,通过ControlValueProperty得到控件的绑定属性,将之前经过转换的值给控件的这个属性就可以了。整个数据绑定实现在如下一个OnBindData方法中。关于属性操作则借助于PropertyAccessor这个组件。

   1: protected virtual void OnBindData(IEnumerable<BindingMapping> bindingMappings, object entity)
   2: {
   3:     foreach (var mapping in bindingMappings)
   4:     {
   5:         var bindingMapping = mapping.Clone();
   6:         object value = PropertyAccessor.Get(entity, bindingMapping.DataSourceProperty); 
   7:         if (null != this.DataItemBinding)
   8:         {
   9:             var args = new DataBindingEventArgs(bindingMapping, value);
  10:             this.DataItemBinding(this, args);
  11:             value = args.DataValue;
  12:         }
  13:         if (!bindingMapping.AutomaticBind)
  14:         {
  15:             continue;
  16:         }
  17:  
  18:         if (!string.IsNullOrEmpty(bindingMapping.FormatString))
  19:         {
  20:             value = Format(value, bindingMapping.FormatString);
  21:         }
  22:         
  23:         Type controlValuePropertyType = PropertyAccessor.GetPropertyType(bindingMapping.Control.GetType(), bindingMapping.ControlValueProperty);
  24:         value = ChangeType(value, controlValuePropertyType);
  25:         if (null == value && typeof(ValueType).IsAssignableFrom(controlValuePropertyType))
  26:         {
  27:             value = Activator.CreateInstance(controlValuePropertyType);
  28:         }
  29:         PropertyAccessor.Set(bindingMapping.Control, bindingMapping.ControlValueProperty, value);
  30:         if (null != this.DataItemBound)
  31:         {
  32:             this.DataItemBound(this, new DataBindingEventArgs(bindingMapping, value));
  33:         }
  34:     }
  35: }

DataBinder设计的目标是让默认的绑定行为解决80%的问题,并且提供给相应的方式去解决余下的问题。为了让开发者能够有效解决余下的这20%的绑定问题,我们定义两个事件:DataItemBinding和DataBound,它们分别在进行绑定之前和之后被触发。关于事件的触发,已经体现在OnBindData方法的定义中了。

五、通过映射集合实现数据捕捉

数据绑定使用到的实际上是Entity-〉Control映射,如果我们借助控件到Control-〉Entity,就能实现自动捕获控件的值然后将其保存到给定的实体对象上。我为此在DataBinder上定义了两个重载的UpdateData方法。

   1: public class DataBinder
   2: {
   3:     //...
   4:     public void BindData( object entity,IEnumerable<BindingMapping> bindingMappings);
   5:     public void UpdateData( object entity, Control container, string suffix = "");
   6: }

UpdateData方法的实现和BindData方法的逻辑基本一致,将Control和Entity呼唤一下而已,所以在这里我就不再赘言叙述了。

一句代码实现批量数据绑定[上篇]

一句代码实现批量数据绑定[下篇]

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2011-03-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、通过DataPropertyAttribute特性过滤实体的数据属性
  • 二、Control/DataSource映射的表示:BindingMapping
  • 三、如何建立Control/DataSource映射集合
  • 四、通过映射集合实现数据绑定
  • 五、通过映射集合实现数据捕捉
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档