通过反射来手写简单的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; / ...
随机推荐
- C++ 生成随机数 srand()和rand()
1. rand() rand(产生随机数)表头文件: #include<stdlib.h>定义函数 :int rand(void) 函数说明 :因为rand() 的内部实现是用线性同余法做 ...
- selenium-05-常见问题
一:日期控件 selenium不能直接对日期控件操作,可以通过js对日期控件做赋值操作 WebElement inputTimeBox=driver.findElement(by.name(" ...
- vue中关于滚动条的那点事
vue中关于滚动条的那点事 不知道你有没有遇到过这种情况,有时当页面切换时,滚动条不在页面的顶端.最近半路加入一个项目,就遇到这种情况.(若只是为了解决此问题,可直接翻到最下方)下面谈谈解决此问题的过 ...
- spring 定时器知识点
一.各域说明 字段域 秒 分 时 日 月 星期(7为周六) 年(可选) 取值范围 0-59 0-59 0-23 1-31 1-12或JAN–DEC 1-7或SUN–SAT 1970–2099 可用字符 ...
- 从零开始搭建WebAPI Core_SqlSugar管理系统 (持续更新中......)
从零开始搭建WebAPI Core_SqlSugar管理系统 前言 本系列皆在从零开始逐步搭建,后台管理系统服务端部分,后续还会推出前端部分. 这次的目的是搭出一个功能完善的 本次系列技术栈以下几个部 ...
- ORM查询2
目录 十三式 2式(针对外键查询优化) select_related和prefetch_related prefetch_related 查询返回值类型 不等式查询 关键字查询 时间查询 跨表查询 组 ...
- 戈多编程-小谈sql语句的优化分析
在sqlserver大数据查询中,避免不了查询效率减慢,暂且抛弃硬件原因和版本原因,仅从sql语句角度分析. 一. sql 语句性能不达标,主要原因有一下几点: 1. 未建索引,检索导致全表扫描 2. ...
- 安装高可用Hadoop生态 (一 ) 准备环境
为了学习Hadoop生态的部署和调优技术,在笔记本上的3台虚拟机部署Hadoop集群环境,要求保证HA,即主要服务没有单点故障,能够执行最基本功能,完成小内存模式的参数调整. 1. 准备环境 1 ...
- 窥见云技术未来大势,腾讯云Techo开发者大会即将在京召开
云.物联网.5G.人工智能……一项项技术的突破带来了天翻地覆的变化,开发者们是如何一次次地进行天马行空的创意和极限突破?2019年11月6日-7日,由腾讯云主办的首届Techo开发者大会将在北京嘉里大 ...
- Mysql多数据库备份
备份数据脚本 #!/bin/bash # date是linux的一个命令 date [参数] [+格式] time=` date +%Y_%m_%d_%H_%M_%S ` # 备份输出路径 backu ...