在本篇中,我們不僅演示實體的結構,而且我們利用集合屬性來打造萬能實體(類似于DataTable)。 下面是代碼:
1)首先我們定義Column,主要提供字段列信息:DynamicDataColumn.cs
~~~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MEntities
{
?? [Serializable]
?? public partial class DynamicDataField
?? {
?????? public string FieldName { get; set; }
?????? public string StrValue { get; set; }
?????? public DateTime DTValue { get; set; }
?????? public Byte[] ByteArrayValue { get; set; }
?????? public string DataType { get; set; }
?? }
}
~~~
2)定義數據字段,用于字段數據的存儲,如果數據類型都可以整成字符串的話,其實可以簡化這塊,而是參照我前面的文章中提到的,利用字典集合來做,但這里提供的方式會更專業一些:DynamicDataField.cs
~~~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MEntities
{
?? [Serializable]
?? public partial class DynamicDataField
?? {
?????? public string FieldName { get; set; }
?????? public string StrValue { get; set; }
?????? public DateTime DTValue { get; set; }
?????? public Byte[] ByteArrayValue { get; set; }
?????? public string DataType { get; set; }
?? }
}
~~~
DynamicDataField.Shared.cs:因為有些輔助方法無法自動生成,可通過代碼共享來達到索引器穿越的目的
~~~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MEntities
{
?? public partial class DynamicDataField
?? {
?????? public object Value
?????? {
?????????? get
?????????? {
?????????????? if (this.DataType == "datatime")
?????????????? {
?????????????????? return this.DTValue;
?????????????? }
?????????????? if (this.DataType == "byte[]")
?????????????? {
?????????????????? return this.ByteArrayValue;
?????????????? }
?????????????? return this.StrValue;
?????????? }
?????????? set
?????????? {
?????????????? if (this.DataType == "datatime")
?????????????? {
?????????????????? DTValue = (DateTime) value;
?????????????? }
?????????????? if (this.DataType == "byte[]")
?????????????? {
?????????????????? this.ByteArrayValue =(byte[])value;
?????????????? }
?????????????? this.StrValue = value.ToString();
?????????? }
?????? }
?? }
}
~~~
因為數據類型穿越沒什么實際意義,所以這里用字符串來表達數據類型,而沒有用Type類型。因為數據類型可以是數據庫的數據類型,用字符串表達更為自由。
待續.....