今天我們來學習學習通過反射技術來生成SQL語句。
反射提供了封裝程序集、模塊和類型的對象。您可以使用反射動態地創建類型的實例,將類型綁定到現有對象,或從現有對象中獲取類型。然后,可以調用類型的方法或訪問其字段和屬性。
1.先建立實體類
用戶實體類:
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; }
}
書籍實體類:
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.測試
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類
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.測試

