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

数据库
《上篇》主要介绍如何通过DataBinder实现批量的数据绑定,以及如何解决常见的数据绑定问题,比如数据的格式化。接下来,我们主要来谈谈DataBinder的设计,看看它是如何做到将作为数据源实体的属性值绑定到界面对应的控件上的。

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

目录:

  1. 通过DataPropertyAttribute特性过滤实体的“数据属性”
  2. Control/DataSource映射的表示:BindingMapping
  3. 如何建立Control/DataSource映射集合
  4. 通过映射集合实现数据绑定
  5. 通过映射集合实现数据捕捉

#p#

一、通过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.  }  

 #p#

二、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采用了克隆模式。

#p#

三、如何建立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.     suffixsuffix = 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. }  

#p#

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

通过《上篇》我们知道,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方法的定义中了。

#p#

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

数据绑定使用到的实际上是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呼唤一下而已,所以在这里我就不再赘言叙述了。
 

原文链接:http://www.cnblogs.com/artech/archive/2011/03/27/databinding2.html

【编辑推荐】

  1. DBA应用技巧:如何升级InnoDB Plugin
  2. 一句代码实现批量数据绑定[上篇]
  3. DBA必备:MySQL数据库常用操作和技巧
  4. MySQL日志操作教程:DBA们管理的利器
  5. MySQL触发器如何正确使用

 

责任编辑:艾婧 来源: 博客园
相关推荐

2011-03-24 10:24:45

批量数据绑定

2012-02-09 09:41:22

2023-11-06 08:31:58

业务代码多线程

2021-05-11 15:34:04

Task.Result代码Winform

2013-03-22 10:53:42

PyConPython

2011-06-13 09:25:01

断号

2009-03-10 18:10:12

LinuxUbuntu技巧

2009-10-29 09:57:16

VB.NET实现数据绑

2013-05-10 10:56:09

2021-12-17 08:55:26

Python微博机器人

2019-11-15 18:00:18

MySQLSQL数据库

2023-07-12 08:01:28

FOADMROADMOXC

2023-09-05 23:34:52

Kubernetes云原生

2014-12-16 08:58:17

甲骨文Oracle数据库选件

2015-08-03 10:21:04

设计模式表达

2022-08-01 10:01:11

JavaScript语言代码库

2020-11-27 09:57:11

Python代码PyPy

2016-09-12 15:26:06

戴尔

2023-08-25 17:10:14

LLM人工智能

2019-08-15 11:42:56

程序员电脑软件
点赞
收藏

51CTO技术栈公众号