目前有不少開源的ORM項目,大多狀況下也不須要咱們重複去造輪子,咱們只須要了解輪子怎麼造的,怎麼用就能夠,下面簡單說一下怎麼經過實體生成一個SQL語句;html
先創建2個Attribute類,TableAttribute、ColumnAttribute , 且但願TableAttribute只想標記在實體類上,因此限制 [AttributeUsage(AttributeTargets.Class)],而但願ColumnAttribute只標記在屬性上 [AttributeUsage(AttributeTargets.Property)]sql
[AttributeUsage(AttributeTargets.Class)] public class TableAttribute : Attribute { private string _TableName = ""; public TableAttribute(string TableName) { this._TableName = TableName; } public string GetTableName() { return this._TableName; } }
[AttributeUsage(AttributeTargets.Property)] public class ColumnAttribute:Attribute { private string _ColumnName = ""; public ColumnAttribute(string ColumnName) { this._ColumnName = ColumnName; } public string GetColumnName() { return this._ColumnName; } }
再作一個靜態擴展類,增長2個擴展方法 一個針對類型的、一個針對屬性的擴展方法app
public static class AttributeExtend { public static string GetMappingName<T>(this T t) where T : BaseModel { if (t.GetType().IsDefined(typeof(TableAttribute), true)) { TableAttribute attribute = (TableAttribute)t.GetType().GetCustomAttributes(typeof(TableAttribute), true)[0]; return attribute.GetTableName(); } else { return t.GetType().Name; } } public static string GetMappingName(this PropertyInfo prop) { if (prop.IsDefined(typeof(ColumnAttribute), true)) { ColumnAttribute attribute = (ColumnAttribute)prop.GetCustomAttribute(typeof(ColumnAttribute), true); return attribute.GetColumnName(); } else { return prop.Name; } } public static string GetMappingName(this Type type) { if (type.IsDefined(typeof(TableAttribute), true)) { TableAttribute attribute = (TableAttribute)type.GetCustomAttribute(typeof(TableAttribute), true); return attribute.GetTableName(); } else { return type.Name; } } }
獲取sql語句方法,目前只簡單寫了查詢全部的,及根據ID查詢,若是想豐富查詢操做須要用到表達式目錄樹this
public class OrmSql { public string GetAllSelectSQL<T>() where T :BaseModel { Type type = typeof(T); var props = type.GetProperties(); string columnString = string.Join(",", props.Select(m => $"[{m.GetMappingName()}]")); string SelectSQL = $"select {columnString} from {type.GetMappingName()}"; return SelectSQL; } public string GetSelectSQLByID<T>(T t) where T :BaseModel { Type type = typeof(T); var props = type.GetProperties(); string columnString = string.Join(",", props.Select(m => $"[{m.GetMappingName()}]")); string SelectSQL = $"select {columnString} from {type.GetMappingName()} where id= '{t.Id}'"; return SelectSQL; } }
調用方法spa
public class Program { public static void Main(string[] args) { OrmSql orm = new OrmSql(); Console.WriteLine(orm.GetAllSelectSQL<Donator>() ); Console.WriteLine(orm.GetSelectSQLByID<Donator>(new Donator() { Id=1}) ); } }
運行截圖:code
原文出處:https://www.cnblogs.com/lxshwyan/p/10955323.htmlorm