第一:从数据库取出数据自动映射相关代码
逐步升级,从简单封装,到利用泛型封装,
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;namespace AdoAttribute
{class DBHelper{private string connectionString = ConfigurationManager.ConnectionStrings["ConnectionSetting"].ConnectionString;public int Update(string updatesql){ int count = 0;using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();SqlCommand command = new SqlCommand(updatesql, connection);//command.Connection.Open();count = command.ExecuteNonQuery();}return count;}public DataSet Select(string selectsql){DataSet ds=new DataSet();using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();SqlCommand command = new SqlCommand(selectsql, connection);//command.Connection.Open();SqlDataAdapter adapter = new SqlDataAdapter();adapter.SelectCommand = command;adapter.Fill(ds); }return ds;}//T public Table1 Find(string ID){ //这个拼接方式,明显比不上String.Join()方法//string colstr = string.Empty;//foreach (PropertyInfo prop in typeof(Table1).GetProperties())//{// colstr += prop.Name + ",";//}//colstr = colstr.Substring(0,colstr.Length-1);string colstr = string.Join(",", typeof(Table1).GetProperties().Select(p=>p.Name));//根据T类型找到对应的属性,拼接出来需要查找的字段信息string sql = string.Format("select {0} from {1} where GUID='{2}'", colstr, "Demo_Table1", ID);Table1 table1=new Table1();using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();SqlCommand command = new SqlCommand(sql, connection);//command.Connection.Open();SqlDataReader reader= command.ExecuteReader();//确定只有一条记录,前进一条即读取第一行if (reader.Read()){//获取每个属性进行赋值,这个对象利用CreateInstance进行生成,同时赋值给prop方法中的SetValue()foreach (PropertyInfo prop in typeof(Table1).GetProperties()){//这个方法说的很清楚,索引化给指定对象的属性赋值prop.SetValue(table1, reader[prop.Name]);//这里除了再次获取特性名称,还可以在查询语句时select Name as NickName绑定更方便}}//while (reader.Read())//{//}//count = command.ExecuteNonQuery();}return table1;}public Table1 FindAttr(string ID){string colstr = string.Join(",", typeof(Table1).GetProperties().Select(p => p.GetPropAttr()));string sql = string.Format("select {0} from {1} where GUID='{2}'", colstr, typeof(Table1).GetClassAttr(), ID);Table1 table1 = new Table1();using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();SqlCommand command = new SqlCommand(sql, connection);SqlDataReader reader = command.ExecuteReader();if (reader.Read()){foreach (PropertyInfo prop in typeof(Table1).GetProperties()){prop.SetValue(table1, reader[prop.GetPropAttr()]);}} }return table1;}//public T Find<T>(string ID)//{// string colstr = string.Join(",", typeof(T).GetProperties().Select(p => p.GetPropAttr()));// string sql = string.Format("select {0} from {1} where GUID='{2}'", colstr, typeof(T).GetClassAttr(), ID);// T t = (T)Activator.CreateInstance(typeof(T));// using (SqlConnection connection = new SqlConnection(// connectionString))// {// connection.Open();// SqlCommand command = new SqlCommand(sql, connection);// SqlDataReader reader = command.ExecuteReader();// if (reader.Read())// {// foreach (PropertyInfo prop in typeof(T).GetProperties())// {// prop.SetValue(t, reader[prop.GetPropAttr()]);// }// }// else {// t = default(T);// }// }// return t;//}public T Find<T>(string ID){string colstr = string.Join(",", typeof(T).GetProperties().Select(p => p.GetAttrValue<PropertyInfo>()));string sql = string.Format("select {0} from {1} where GUID='{2}'", colstr, typeof(T).GetAttrValue<Type>(), ID);T t = (T)Activator.CreateInstance(typeof(T));using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();SqlCommand command = new SqlCommand(sql, connection);SqlDataReader reader = command.ExecuteReader();if (reader.Read()){foreach (PropertyInfo prop in typeof(T).GetProperties()){ prop.SetValue(t, reader[prop.GetAttrValue<PropertyInfo>()]);}}else{t = default(T);}}return t;}}
}
第二:自定义特性 相关代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;namespace AdoAttribute
{[AttributeUsage(AttributeTargets.All)]//其实针对类,和属性分别定义特性类,可以共用一个抽象的类public class AttributeName:Attribute{public string _Name;public AttributeName(string name) {_Name = name;}public string GetName() {return _Name;}}//扩展方法,获取模型类的特性,还有获取属性的特性public static class AttributeExtenssion {public static string GetClassAttr(this Type type) {//存在这个特性,那么获取特性对象,及里面名字,否则返回自身名字if (type.IsDefined(typeof(AttributeName), true)){AttributeName attrname = (AttributeName)type.GetCustomAttributes(typeof(AttributeName), true).First();return attrname.GetName();}else {return type.Name;}}public static string GetPropAttr(this PropertyInfo prop){ //存在这个特性,那么获取特性对象,及里面名字,否则返回自身名字if (prop.IsDefined(typeof(AttributeName), true)){AttributeName attrname = (AttributeName)prop.GetCustomAttributes(typeof(AttributeName), true).First();return attrname.GetName();}else{return prop.Name;}}//明显看出上面两个方法,惊人的相似,同样改为泛型方法,这里的T必须是反射里面的类型即继承自MemberInfo,否则无法调用IsDefined()方法public static string GetAttrValue<T>(this T prop) where T:MemberInfo{//存在这个特性,那么获取特性对象,及里面名字,否则返回自身名字if (prop.IsDefined(typeof(AttributeName), true)){AttributeName attrname = (AttributeName)prop.GetCustomAttributes(typeof(AttributeName), true).First();return attrname.GetName();}else{return prop.Name;}}}
}
第三,模型相关代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace AdoAttribute
{class ViewModel{}[AttributeName("Demo_Table1")]class Table1 {[AttributeName("Name")]public string NickName { get; set; }public int Age { get; set; }public Decimal Money { get; set; }}
}
第四:后台脚本代码
CREATE TABLE [dbo].[Demo_Table1]([GUID] [varchar](50) NOT NULL,[Name] [varchar](150) NULL,[Age] [int] NULL,[Money] [decimal](18, 4) NULL,[AddTime] [datetime] NULL,CONSTRAINT [PK_Demo_Table1] PRIMARY KEY CLUSTERED
([GUID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]GO