数据库字段映射到类实体
香水坏坏 发表于 2007-7-7
[ASP.NET]
作者: 香水坏坏
转载请著名,谢谢!
C#代码
- using System;
- using System.Data;
- using System.Collections.Generic;
- using System.Text;
- using System.Reflection;
C#代码
- namespace YourNamespace
- {
- public abstract class BaseModule
- {
- private long _id;
- [MSSQLField("id")]
- public long UniqueID
- {
- get { return _id; }
- set { _id = value; }
- }
- public BaseModule(){}
- public BaseModule(IDataReader dr)
- {
- Type t = this.GetType();
- PropertyInfo[] properties = t.GetProperties();
- for (int i = 0; i < dr.FieldCount; i++)
- {
- string fieldname = dr.GetName(i).ToLower();
- object fieldvalue = dr.GetValue(i);
- if (fieldvalue != DBNull.Value)
- {
- for (int j = 0; j < properties.Length; j++)
- {
- if (BindDataReaderValue(this, properties[j], fieldvalue, fieldname))
- break;
- }
- }
- }
- }
- private bool BindDataReaderValue(object des, PropertyInfo property, object val , string tbField)
- {
- MSSQLFieldAttribute[] atts = (MSSQLFieldAttribute[])property.GetCustomAttributes(typeof(MSSQLFieldAttribute), true);
- if (property.CanWrite && atts.Length > 0)
- {
- if (atts[0].IsComplexClass == false)
- {
- if (atts[0].FieldName == tbField)
- {
- if (property.PropertyType.IsEnum)
- {
- property.SetValue(des, Enum.ToObject(property.PropertyType, val), null);
- }
- else
- {
- property.SetValue(des, val, null);
- }
- return true;
- }
- }
- else
- {
- object complexObject = property.GetValue( this , null );
- if (null == complexObject)
- {
- complexObject = property.PropertyType.GetConstructor(System.Type.EmptyTypes).Invoke(null);
- property.SetValue(this, complexObject, null);
- }
- return BindDataReaderClass(complexObject, val, tbField);
- }
- }
- return false;
- }
- private bool BindDataReaderClass(object des, object val, string tbField)
- {
- PropertyInfo[] properties = des.GetType().GetProperties();
- for (int i = 0; i < properties.Length; i++)
- {
- if (BindDataReaderValue(des, properties[i], val, tbField))
- return true;
- }
- return false;
- }
- }
- [AttributeUsage( AttributeTargets.Property , AllowMultiple=false ) ]
- public class MSSQLFieldAttribute : Attribute
- {
- private string _fieldname;
- private bool _isComplexClass;
- public bool IsComplexClass
- {
- get { return _isComplexClass; }
- set { _isComplexClass = value; }
- }
- public string FieldName
- {
- get { return _fieldname; }
- set { _fieldname = value.ToLower(); }
- }
- public MSSQLFieldAttribute() { _isComplexClass = true; }
- public MSSQLFieldAttribute(string fieldname)
- {
- _fieldname = fieldname;
- }
- }
- }