通过反射来手写简单的ORM SQlserver
直接上干货,其中很多地方都没有进行相关的判断以及try catch等,谢谢! //-----MySQlServerORM 【简单 CURD】 using System;
using System.Collections.Generic;
using System.Linq;
namespace COMMOM
{
using C10.ZRF.Model.Filter;
using System.Configuration;
using System.Data.SqlClient;
using Dapper;
using System.Reflection;
using static COMMOM.SqlEnum; public static class MySQlServerORM
{
private static readonly string con = ConfigurationManager.ConnectionStrings["sqlc"].ConnectionString; #region 查询单个实体 T GetEntityByID<T>(int id)
public static T GetEntityByID<T>(int id) where T : class, new()
{
string pkName = ReflectionAttriHelper.GetPrimaryKey(typeof(T));
string sql = SuperSQlGet<T>.GetSQL(SQLType.GetEntityByID_SQL);
using (SqlConnection conn = new SqlConnection(con))
{
DynamicParameters parem = new DynamicParameters();
parem.Add(pkName, id);
T result = conn.QueryAsync<T>(sql, parem).Result.FirstOrDefault();
return result ?? default(T);
}
}
#endregion #region 查询一张表的所有集合数据 IEnumerable<T> GetAllList<T>()
public static List<T> GetAllList<T>() where T : class, new()
{
string sql = SuperSQlGet<T>.GetSQL(SQLType.GetAllList_SQL);
using (SqlConnection conn = new SqlConnection(con))
{
return (conn.QueryAsync<T>(sql).Result.ToList()) ?? default(List<T>);
}
}
#endregion #region 新增 bool Insert<T>(T entity)
public static bool Insert<T>(T entity) where T : class,new()
{
string sql = SuperSQlGet<T>.GetSQL(SQLType.Insert_SQl);
PropertyInfo[] pylist = typeof(T).GetProperties().IgnorePKID();
using (SqlConnection conn = new SqlConnection(con))
{
DynamicParameters pa = new DynamicParameters();
pylist.ToList().ForEach(p => { pa.Add($"{p.Name}", p.GetValue(entity)); });
return conn.ExecuteAsync(sql,pa).Result > ? true : false;
}
}
#endregion #region 删除操作DeleteByPrimaryKey<T>(int id)
public static bool DeleteByPrimaryKey<T>(int id) where T : class, new()
{
string sql = SuperSQlGet<T>.GetSQL(SQLType.DeleteByPrimaryKey_SQL);
using (SqlConnection conn = new SqlConnection(con))
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add(ReflectionAttriHelper.GetPrimaryKey(typeof(T)), id);
return conn.ExecuteAsync(sql, parameters).Result > ;
}
}
//删除操作DeleteByEntity<T>(T entity)
public static bool DeleteByEntity<T>(T entity) where T : class, new()
{
if (entity != null)
{
try
{
Type ty = entity.GetType();
object obj = null;
// ty.GetProperties().Any(c =>..... 两个都可以,还是使用下面的防止报错,效率也高些
ty.GetProperties().FirstOrDefault(c =>
{
if (c.IsDefined(typeof(PKAttribute)))
{
obj = c.GetValue(entity); return true;
}
else { return false; }
});
return obj != null ? DeleteByPrimaryKey<T>(int.Parse(obj.ToString())) : false;
}
catch (Exception ex) { throw new Exception("删除操作失败,原因:" + ex.Message); }
}
return false;
}
#endregion
}
} //---SuperSQlGet<T> 静态构造函数来初始化SQL语句 【获取SQL语句】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static COMMOM.SqlEnum; namespace COMMOM
{
public static class SuperSQlGet<T> where T : class, new()
{
private static string GetEntityByID_SQL = string.Empty;
private static string GetAllList_SQL = string.Empty;
private static string Insert_SQl = string.Empty;
private static string DeleteByPrimaryKey_SQL = string.Empty; static SuperSQlGet()
{
//-----------1GetEntityByID
Type ty = typeof(T);
string pkName = ReflectionAttriHelper.GetPrimaryKey(ty);
GetEntityByID_SQL = $"select top 1 * from [{ReflectionAttriHelper.GetTBName(ty)}] where {pkName}=@{pkName}"; //-----------2 GetAllList
GetAllList_SQL = $"select * from [{ReflectionAttriHelper.GetTBName(ty)}] "; //------------3 insert
PropertyInfo[] pylist = ty.GetProperties().IgnorePKID();
string tabPro = string.Join(",", pylist.Select(c => $"{c.Name}"));
string vastrSafe = string.Join(",", pylist.Select(c => $"@{c.Name}"));
Insert_SQl = $"insert into [{ReflectionAttriHelper.GetTBName(ty)}]({tabPro}) values({vastrSafe})"; //----------4 DeleteByPrimaryKey
DeleteByPrimaryKey_SQL = $"delete from [{ReflectionAttriHelper.GetTBName(ty)}] where {pkName}=@{pkName}";
} public static string GetSQL(SQLType sqltype)
{
switch (sqltype)
{
case SQLType.GetEntityByID_SQL: return GetEntityByID_SQL;
case SQLType.GetAllList_SQL: return GetAllList_SQL;
case SQLType.Insert_SQl: return Insert_SQl;
case SQLType.DeleteByPrimaryKey_SQL: return DeleteByPrimaryKey_SQL;
default:
throw new Exception("SQl获取异常.....");
}
}
}
} //------SqlEnum 【生成SQL使用的枚举】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace COMMOM
{
public static class SqlEnum
{
public enum SQLType
{
GetEntityByID_SQL,
GetAllList_SQL,
Insert_SQl,
DeleteByPrimaryKey_SQL
}
}
} //----ReflectionAttriHelper 【帮助类】
using C10.ZRF.Model.Filter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace COMMOM
{
public static class ReflectionAttriHelper
{
#region GetPrimaryKey(Type ty) 获取主键的属性
public static string GetPrimaryKey(Type ty)
{
var prolist = ty.GetProperties();
string proName = string.Empty;
prolist.FirstOrDefault(c =>
{
if (c.IsDefined(typeof(PKAttribute), false))
{
proName = c.Name; return true;
}
else { return false; }
});
return !string.IsNullOrEmpty(proName) ? proName : "id";
}
#endregion #region 获取表的映射名称 string GetTBName(Type type)
public static string GetTBName(Type type)
{
Type ty = typeof(TabNameAttribute);
return type.IsDefined(ty) ? ((TabNameAttribute)type.GetCustomAttribute(ty, false)).name : type.Name;
}
#endregion #region 去掉主键的属性 PropertyInfo[] IgnorePKID(this PropertyInfo[] py )
public static PropertyInfo[] IgnorePKID(this PropertyInfo[] py)
{
List<PropertyInfo> pylist = new List<PropertyInfo>();
py.ToList().ForEach(c => { if (!c.IsDefined(typeof(PKAttribute))) pylist.Add(c); });
return pylist.ToArray();
}
#endregion
}
} //-----Filter 【过滤器及Attribute】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace C10.ZRF.Model.Filter
{
using System.Reflection;
[AttributeUsage(AttributeTargets.Class)]
public class TabNameAttribute : Attribute
{
public string name { get; set; }
public TabNameAttribute(string tabName)
{
this.name = tabName;
}
} [AttributeUsage(AttributeTargets.Property)]
public class PKAttribute : Attribute
{
} [AttributeUsage(AttributeTargets.Property)]
public class ProNameAttribute : Attribute
{
public string pname { get; set; }
public ProNameAttribute(string pname)
{
this.pname = pname;
}
}
} //----model【实体】
using System;
namespace C10.ZRF.Model.ModelView
{
using Filter;
[TabName("User")]
public class UserView
{
[PK]
public int uid { get; set; }
public string userName { get; set; }
public string userPwd { get; set; }
public string userPhone { get; set; }
public int? userAge { get; set; }
public bool isdel { get; set; }
[ProName("creatime")]
public DateTime? addTime { get; set; }
public override string ToString()
{
return $"uid={this.uid},userName={this.userName},userPwd={this.userPwd},userPhone={this.userPhone},userAge={this.userAge},";
}
}
} //-----UI 【显示的界面】
#region ORM
public ActionResult GetEntityByID()
{
UserView obj = MySQlServerORM.GetEntityByID<UserView>();
List<UserView> ulist = MySQlServerORM.GetAllList<UserView>();
ViewBag.objinfo =obj==null?"没有查找到": $"uid={obj.uid},姓名={obj.userName},TEL={obj.userPhone}";
string str = string.Empty;
ulist.ForEach(c => { str += (c.ToString() + "<br/>"); });
ViewBag.list = str;
return View();
} public ActionResult AddEntity()
{ //------参数需要全部提供 需要参数 '@userName',但未提供该参数
bool flag = MySQlServerORM.Insert<UserView>(new UserView()
{
addTime = DateTime.Now,
isdel = false,
userAge = ,
userName = "qqAdd",
userPhone = "",
userPwd = "pwd123"
});
ViewBag.addflag = flag ? "Addok" : "AddError";
return View();
} public ActionResult DeleteORM()
{
// string deleteResult= MySQlServerORM.DeleteByPrimaryKey<UserView>(5) ? "成功" : "失败";//--根据PK来删除
UserView obj = new UserView { uid = };
//--------根据实体来删除
string deleteResult = MySQlServerORM.DeleteByEntity<UserView>(obj) ? "成功" : "失败";
ViewBag.deleteok = $"数据删除{deleteResult}";
return View();
}
#endregion
通过反射来手写简单的ORM SQlserver的更多相关文章
- 不使用Tomcat,手写简单的web服务
背景: 公司使用的YDB提供了http的查询数据库服务,直接通过url传入sql语句查询数据-_-||.ydb的使用参照:https://www.cnblogs.com/hd-zg/p/7115112 ...
- 手写简单call,apply,bind
分析一下call的使用方法:call是显示绑定this指向,然后第一个参数是你所指向的this对象,后面跟着多个参数,以逗号隔开 function sum(num1,num2){ return num ...
- 第三节:工厂+反射+配置文件(手写IOC)对缓存进行管理。
一. 章前小节 在前面的两个章节,我们运用依赖倒置原则,分别对 System.Web.Caching.Cache和 System.Runtime.Cacheing两类缓存进行了封装,并形成了ICach ...
- 手写简单的jq雪花飘落
闲来无事,准备写个雪花飘落的效果,没有写太牛逼的特效,极大的简化了代码量,这样容易读取代码,用起来也很简单,对于那些小白简直是福利啊,简单易读易学.先直接上代码吧,然后再一一讲解,直接复制粘贴就可以拿 ...
- 利用Java手写简单的httpserver
前言: 在看完尚学堂JAVA300中讲解如何实现一个最简单的httpserver部分的视频之后, 一.前置知识 1.HTTP协议 当前互联网网页访问主要采用了B/S的模式,既一个浏览器,一个服务器,浏 ...
- 手写简单PE
环境工具:Windows 10 010Editor 目标程序功能: 调用MessageBoxA弹出消息框. 1.构造DOS头 typedef struct _IMAGE_DOS_HEADER { // ...
- 手写简单IOC
ReflectUtils.java (反射工具类) package top.icss.ioc; import java.io.File; import java.io.FileFilter; impo ...
- Spring源码分析 手写简单IOC容器
Spring的两大特性就是IOC和AOP. IOC Container,控制反转容器,通过读取配置文件或注解,将对象封装成Bean存入IOC容器待用,程序需要时再从容器中取,实现控制权由程序员向程序的 ...
- 手写简单的promise
function Promise(fn) { var that = this; this.status = "pedding"; this.value = undefined; / ...
随机推荐
- Build a Contest-创建比赛 CodeForce1100B
题目链接:Build a Contest 题目原文 Arkady coordinates rounds on some not really famous competitive programmin ...
- The type java.lang.AutoCloseable cannot be resolved. It is indirectly referenced from required .class files
出现问题: The type java.lang.AutoCloseable cannot be resolved. It is indirectly referenced from required ...
- 工厂模式(整理自李建忠<C++设计模式>视频)
整理自李建忠<C++设计模式>视频 一.导入:"对象创建"模式和工厂模式 工厂模式只是该模式下的一种. 二.举例说明 有这样一个场景:需要在MainForm中设计一个按 ...
- Linux 伪终端(pty)
通过<Linux 终端(TTY)>一文我们了解到:我们常说的终端分为终端 tty1-6 和伪终端.使用 tty1-6 的情况一般为 Linux 系统直接连了键盘和显示器,或者是使用了 vS ...
- 如何免费使用GPU跑深度学习代码
从事深度学习的研究者都知道,深度学习代码需要设计海量的数据,需要很大很大很大(重要的事情说三遍)的计算量,以至于CPU算不过来,需要通过GPU帮忙,但这必不意味着CPU的性能没GPU强,CPU是那种综 ...
- js中对于数组的操作
let myArray=[11,22,33]; console.log('原数组:',myArray); myArray.push(44,55); console.log('用push在数组后面插入元 ...
- 触电JavaScript-如何将json 二维数组转换为 JSON object
最近因为项目中使用的是 ActiveReports .Net 产品,因为他们最近新出了 ActiveReports JS 版本,所以内心有点痒痒,想试试这个纯前端版本报表控件到底如何,毕竟我们项目有 ...
- 揭秘C# SQLite的从安装到使用
SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了 ...
- .net core session的使用步骤
步骤 操作 备注 1 Microsoft.AspNetCore.Session Microsoft.AspNetCore.Http.Extensions nuget安装包 2 ConfigureS ...
- js构造函数的浅薄理解
任何函数,只要通过 new 操作符来调用,那它就可以作为构造函数 如:任何函数,只要通过 new 操作符来调用,那它就可以作为构造函数 : fuction Preson(){...} var pres ...