今天咱們來學習學習經過反射技術來生成SQL語句。sql
反射提供了封裝程序集、模塊和類型的對象。您能夠使用反射動態地建立類型的實例,將類型綁定到現有對象,或從現有對象中獲取類型。而後,能夠調用類型的方法或訪問其字段和屬性。學習
1.先創建實體類測試
用戶實體類:ui
public class User { public int id { get; set; } public string UserName { get; set; } public string Password { get; set; } public int Age { get; set; } public string PhoneNumber { get; set; } public string Address { get; set; } }
書籍實體類:3d
public class Book { public int id { set; get; } public string BookName { get; set; } public string ISBN { set; get; } public string Author { set; get; } public double Price { set; get; } }
2.經過反射技術來生成Insert語句(舉個例子而已,只生成Insert語句)對象
/// <summary> /// 泛型方法,反射生成SQLInsert語句 /// </summary> /// <typeparam name="T">實體類型</typeparam> /// <param name="entity">實體對象</param> /// <returns></returns> public string CreateInsertSQL<T>(T entity) { //1.先獲取實體的類型描述 Type type = entity.GetType(); //2.得到實體的屬性集合 PropertyInfo[] props = type.GetProperties(); //實例化一個StringBuilder作字符串的拼接 StringBuilder sb = new StringBuilder(); sb.Append("insert into " + type.Name + " ("); //3.遍歷實體的屬性集合 foreach (PropertyInfo prop in props) { //4.將屬性的名字加入到字符串中 sb.Append(prop.Name + ","); } //**去掉最後一個逗號 sb.Remove(sb.Length - 1, 1); sb.Append(" ) values("); //5.再次遍歷,造成參數列表"(@xx,@xx@xx)"的形式 foreach (PropertyInfo prop in props) { sb.Append("@" + prop.Name + ","); } //**去掉最後一個逗號 sb.Remove(sb.Length - 1, 1); sb.Append(")"); return sb.ToString(); }
3.測試blog
class Program { static void Main(string[] args) { //調用ReflationCreateSQL類中的CreateInsertSQL方法 string sql = new ReflationCreateSQL().CreateInsertSQL(new User()); string sql1 = new ReflationCreateSQL().CreateInsertSQL(new Book()); Console.WriteLine(sql.ToString()); Console.WriteLine(sql1.ToString()); Console.WriteLine("Press any key to continue . . ."); Console.ReadLine(); } }
結果:繼承
可是,咱們發現id是主鍵,假設id是自增加的,咱們生成的SQL(Insert)語句中就不該該有id,在這裏我用自定義Attribute的方法來解決這個問題。字符串
4.先新建一個類,繼承Attribute類get
public class KEYAttribute : Attribute { }
這個類僅此而已就夠了。
5.在實體類中的id這個字段上加上[KEY]標記
public class Book { [KEY] public int id { set; get; } public string BookName { get; set; } public string ISBN { set; get; } public string Author { set; get; } public double Price { set; get; } }
public class User { [KEY] public int id { get; set; } public string UserName { get; set; } public string Password { get; set; } public int Age { get; set; } public string PhoneNumber { get; set; } public string Address { get; set; } }
6.加好標記以後,咱們只須要這CreateInsertSQL<T>(T entity)這個方法中的兩個foreach循環體中加一些判斷便可
foreach (PropertyInfo prop in props) { //獲取用戶自定義標記集合 object[] attrs = prop.GetCustomAttributes(typeof(KEYAttribute), true); //若是屬性上有自定義標記KEYAttribute,退出本次循環 if (attrs.Length > 0) { continue; } //將屬性的名字加入到字符串中 sb.Append(prop.Name + ","); }
foreach (PropertyInfo prop in props) { object[] attrs = prop.GetCustomAttributes(typeof(KEYAttribute), true); if (attrs.Length > 0) { continue; } sb.Append("@" + prop.Name + ","); }
7.測試