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

最新文章

  1. AEAI DP V3.7.0 发布,开源综合应用开发平台
  2. Tensorflow word2vec编译运行
  3. sublime自定义快键键不行,
  4. Thinking in Java——笔记(6)
  5. eclipse中没有R文件
  6. Android——拖动条SeekBar
  7. java web 学习七(HttpServletResponse对象1)
  8. input的多条数据以数组形势上传
  9. dedecms修改templets为别的名字
  10. 小学生之Map集合框架的使用
  11. vue打包遇到的坑
  12. Java基础语法-Unicode、UTF-8、UTF-16
  13. P1325 雷达安装
  14. vue 小知识
  15. Java工程师高手之路
  16. jQuery UI的datepicker()与变更格式
  17. Mysql + Mybatis动态建表
  18. cocos2d-js 3.0 屏幕适配方案 分辨率适应
  19. hbase源码系列(九)StoreFile存储格式
  20. Oracle 11g 更改字符集

热门文章

  1. Unity项目 - DeathtrapDungeon死亡地牢
  2. Spring Data JPA 梳理 - 使用方法
  3. Maven 梳理 -目录结构
  4. Java中类加载和反射技术实例
  5. Kafka 异步消息也会阻塞?记一次 Dubbo 频繁超时排查过程
  6. 向net core 3.0进击——April.WebApi从2.2爬到3.0
  7. 使用LitePal建立表关联
  8. orm加强版
  9. 【Autofac打标签模式】AutoConfiguration和Bean
  10. Spring Boot 常用注解汇总