直接上干货,其中很多地方都没有进行相关的判断以及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的更多相关文章

  1. 不使用Tomcat,手写简单的web服务

    背景: 公司使用的YDB提供了http的查询数据库服务,直接通过url传入sql语句查询数据-_-||.ydb的使用参照:https://www.cnblogs.com/hd-zg/p/7115112 ...

  2. 手写简单call,apply,bind

    分析一下call的使用方法:call是显示绑定this指向,然后第一个参数是你所指向的this对象,后面跟着多个参数,以逗号隔开 function sum(num1,num2){ return num ...

  3. 第三节:工厂+反射+配置文件(手写IOC)对缓存进行管理。

    一. 章前小节 在前面的两个章节,我们运用依赖倒置原则,分别对 System.Web.Caching.Cache和 System.Runtime.Cacheing两类缓存进行了封装,并形成了ICach ...

  4. 手写简单的jq雪花飘落

    闲来无事,准备写个雪花飘落的效果,没有写太牛逼的特效,极大的简化了代码量,这样容易读取代码,用起来也很简单,对于那些小白简直是福利啊,简单易读易学.先直接上代码吧,然后再一一讲解,直接复制粘贴就可以拿 ...

  5. 利用Java手写简单的httpserver

    前言: 在看完尚学堂JAVA300中讲解如何实现一个最简单的httpserver部分的视频之后, 一.前置知识 1.HTTP协议 当前互联网网页访问主要采用了B/S的模式,既一个浏览器,一个服务器,浏 ...

  6. 手写简单PE

    环境工具:Windows 10 010Editor 目标程序功能: 调用MessageBoxA弹出消息框. 1.构造DOS头 typedef struct _IMAGE_DOS_HEADER { // ...

  7. 手写简单IOC

    ReflectUtils.java (反射工具类) package top.icss.ioc; import java.io.File; import java.io.FileFilter; impo ...

  8. Spring源码分析 手写简单IOC容器

    Spring的两大特性就是IOC和AOP. IOC Container,控制反转容器,通过读取配置文件或注解,将对象封装成Bean存入IOC容器待用,程序需要时再从容器中取,实现控制权由程序员向程序的 ...

  9. 手写简单的promise

    function Promise(fn) { var that = this; this.status = "pedding"; this.value = undefined; / ...

随机推荐

  1. 4.7 if else-if

    c#中的if else-if if else-if  中最后的"else":如果用户输入的不等于上面的else if(xxx)表达式,则输出这行代码. **不参与运算的数值不用转换 ...

  2. 性能测试的基础知识--QPS和TPS

    基本概念: QPS:Queries Per Second意思是“每秒查询率” ,是一台服务器每秒能够相应的查询次数,是对一个特定的查询服务器在规定时间内所处理流量多少的衡量标准. TPS:Transa ...

  3. svn报错Item is not readable svn解决方案

    解决: 配置目录权限时如: [/]tangtx=rwyangcx=rwweishq=rw 结果组用户分别在根目录下可以正常show log,而在其子目录中show log都会提示 Item is no ...

  4. Mysql的MyISAM和InnoDB存储引擎的区别

    从以下几个方面: 1.存储结构 每个MyISAM在磁盘上存储成三个文件.第一个文件的名字以表的名字开始,扩展名指出文件类型. .frm文件存储表定义. 数据文件的扩展名为.MYD (MYData).  ...

  5. 002-python函数、高级特性

    1.函数 1.1 定义函数 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回 自定义一个求绝对 ...

  6. ArcGIS Server服务扩展SOE应用场景

    何时需要使用SOE? 用自己的业务逻辑扩展ArcGIS Server • 分析超越了即拿即用的GP工具 • 功能超越了Esri Web APIS中包含的内容 • 通过其他方式细粒度的ArcObject ...

  7. jQuery查找节点(选择器)

    jQuery通过选择器来完成节点的查找: 1.基本选择器: ①通用/所有的选择器:$("*") //使用*号来表示. ②:标签选择器:$("标签名(div)") ...

  8. java基础之泛型对象与json互转

    1. 场景描述 把泛型对象转成字符串放到缓存中,获取后使用有点问题,记录下,有碰到的朋友,参考下. 2. 解决方案 2.1 操作类及说明 /** * @auther: 软件老王 */ public s ...

  9. iOS 设备数据管理工具 iMazing v2.10.3 绿色便携版

    iMazing 是一款可以帮助用户管理 iOS 设备的软件,功能远远超出 iTunes.iMazing 连接你的 iOS 设备(iPhone. iPad 或 iPod)相连,使用起来也非常的方便.你可 ...

  10. Windows中0环与3环通信(常规方式)

    Windows内核分析索引目录:https://www.cnblogs.com/onetrainee/p/11675224.html 一.知识点讲解 1. 设备对象 我们在开发窗口程序的时候,消息被封 ...