目前有不少开源的ORM项目,大多状况下也不须要咱们重复去造轮子,咱们只须要了解轮子怎么造的,怎么用就能够,下面简单说一下怎么经过实体生成一个SQL语句;sql
先创建2个Attribute类,TableAttribute、ColumnAttribute , 且但愿TableAttribute只想标记在实体类上,因此限制 [AttributeUsage(AttributeTargets.Class)],而但愿ColumnAttribute只标记在属性上 [AttributeUsage(AttributeTargets.Property)]app
[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个扩展方法 一个针对类型的、一个针对属性的扩展方法this
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查询,若是想丰富查询操做须要用到表达式目录树spa
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; } }
调用方法code
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}) ); } }
运行截图:orm