本篇內(nèi)容主要講解“C#抽象增刪改怎么實(shí)現(xiàn)”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“C#抽象增刪改怎么實(shí)現(xiàn)”吧!
10年積累的成都網(wǎng)站建設(shè)、成都做網(wǎng)站經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有臨澤免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
現(xiàn)在業(yè)界火了一種ORM 框架,那就是Dapper,我也是Dapper的粉絲之一,而我總結(jié)出來(lái)的框架也是基于Daaper。下面是我的代碼,首先是Dapper Helper類,數(shù)據(jù)庫(kù)通用訪問(wèn)類(用Nuget工具先把Dapper類引用到NetUtility.Dapper.Core項(xiàng)目中去):
NetUtility.Dapper.Core.DataBaseAccess.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;
using NetUtility.Entity;
using System.Reflection;
namespace NetUtility.Dapper.Core
{
/// <summary>
/// 數(shù)據(jù)庫(kù)訪問(wèn)類
/// </summary>
public class DataBaseAccess
{
public static SqlConnection CreateConnection()
{
string connStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
return conn;
}
/// <summary>
/// 執(zhí)行增、刪、改方法
/// </summary>
/// <param name="sql"></param>
/// <param name="parms"></param>
/// <returns></returns>
public static int Execute(string sql, object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.Execute(sql,parms);
}
}
/// <summary>
/// 得到單行單列
/// </summary>
/// <param name="sql"></param>
/// <param name="parms"></param>
/// <returns></returns>
public static object ExecuteScalar(string sql, object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.ExecuteScalar(sql, parms);
}
}
/// <summary>
/// 單個(gè)數(shù)據(jù)集查詢
/// </summary>
/// <param name="sql"></param>
/// <param name="parms"></param>
/// <returns></returns>
public static List<TEntity> Query<TEntity>(string sql,Func<TEntity,bool> pre ,object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.Query<TEntity>(sql, parms).Where(pre).ToList();
}
}
/// <summary>
/// 單個(gè)數(shù)據(jù)集查詢
/// </summary>
/// <param name="sql"></param>
/// <param name="parms"></param>
/// <returns></returns>
public static List<TEntity> Query<TEntity>(string sql, object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.Query<TEntity>(sql, parms).ToList();
}
}
/// <summary>
/// 多個(gè)數(shù)據(jù)集查詢
/// </summary>
/// <param name="sql"></param>
/// <param name="parms"></param>
/// <returns></returns>
public static SqlMapper.GridReader MultyQuery(string sql, object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.QueryMultiple(sql, parms);
}
}
/// <summary>
/// 單個(gè)數(shù)據(jù)集查詢
/// </summary>
/// <param name="sql"></param>
/// <param name="parms"></param>
/// <returns></returns>
public static TEntity FirstOrDefault<TEntity>(string sql,Func<TEntity,bool> selector, object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.Query<TEntity>(sql, parms).Where(selector).FirstOrDefault();
}
}
}
}
我把增刪改查抽象出來(lái)了,少不了的就是SQL語(yǔ)句的生成,生成SQL語(yǔ)句,要么是映射,要么是反射,而我用的是反射,給一個(gè)Entity類,我讀取他所有屬性和字段,然后生成對(duì)應(yīng)的SQL語(yǔ)句。 NetUtility.Dapper.Core.DataMapping.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace NetUtility.Dapper.Core { internal class DataMapping<TModel> where TModel : class { #region 數(shù)據(jù)庫(kù)類型+DataBaseType /// <summary> /// 數(shù)據(jù)庫(kù)類型 /// </summary> public static string DataBaseType { get { string strType = ConfigurationManager.AppSettings["DataBaseType"]; if (!string.IsNullOrEmpty(strType)) { return strType; } else { return string.Empty; } } } #endregion #region 主鍵屬性字段+PrimaryKey /// <summary> /// 主鍵字段名稱 /// </summary> public static string PrimaryKey { get { Type t = typeof(TModel); TableInfoAttribute tableInfo = t.GetCustomAttribute(typeof(TableInfoAttribute), true) as TableInfoAttribute; if (tableInfo!=null)//如果沒有標(biāo)識(shí)表信息特性,則通過(guò)表名向數(shù)據(jù)庫(kù)中得到主鍵信息 { return tableInfo.PrimaryKey; } else { string tableName = TableName(); return DataBaseAccess.ExecuteScalar("SELECT name FROM SysColumns WHERE id=Object_Id('" + tableName + "') and colid=(select top 1 colid from sysindexkeys where id=Object_Id('" + tableName + "'))").ToString(); } } } #endregion #region 獲取表名+TableName /// <summary> /// 獲取表名 /// </summary> /// <param name="prev">數(shù)據(jù)庫(kù)表名前綴</param> /// <returns></returns> public static string TableName(string prev = "") { Type t = typeof(TModel); TableInfoAttribute tableInfo = t.GetCustomAttribute(typeof(TableInfoAttribute), true) as TableInfoAttribute; return tableInfo != null ? tableInfo.TableName : string.Concat(prev, t.Name); } #endregion #region Select 查詢語(yǔ)句+GetQuerySql /// <summary> /// Select 查詢語(yǔ)句 /// </summary> /// <returns></returns> public static string GetQuerySql() { StringBuilder sql = new StringBuilder("select * from "); sql.Append(TableName()); return sql.ToString(); } #endregion #region Insert非Null屬性的對(duì)象實(shí)例 Sql 語(yǔ)句+GetInsertSql /// <summary> /// Insert 非Null屬性的對(duì)象實(shí)例 Sql 語(yǔ)句 /// </summary> /// <param name="model"></param> /// <returns></returns> public static string GetInsertSql(TModel model) { StringBuilder sql = new StringBuilder("insert into "); string[] props = Propertys(model); sql.Append(TableName()); sql.Append("("); sql.Append(string.Join(",", props)); sql.Append(") values(@"); sql.Append(string.Join(",@", props)); sql.Append(");select @@IDENTITY"); return sql.ToString(); } #endregion #region Delete Sql 語(yǔ)句+GetDeleteSql /// <summary> /// Delete Sql 語(yǔ)句 /// </summary> /// <returns></returns> public static string GetDeleteSql() { return string.Format(@"delete from {0} where {1} in @IdList", TableName(), PrimaryKey); } #endregion #region Update 非Null屬性的對(duì)象實(shí)例 Sql語(yǔ)句+GetUpdateSql /// <summary> /// Update 非Null屬性的對(duì)象實(shí)例 Sql語(yǔ)句 /// </summary> /// <param name="model"></param> /// <returns></returns> public static string GetUpdateSql(TModel model) { StringBuilder sql = new StringBuilder("update "); string[] props = Propertys(model); sql.Append(TableName()); sql.Append(" set "); foreach (string propName in props) { sql.Append(propName + "=@" + propName + ","); } sql.Remove(sql.Length - 1, 1); sql.Append(" where " + PrimaryKey + "=@Id"); return sql.ToString(); } #endregion #region 非主鍵且非Null屬性集合+Propertys /// <summary> /// 非主鍵且非Null屬性 /// </summary> /// <param name="model"></param> /// <returns></returns> public static string[] Propertys(TModel model) { PropertyInfo[] props = typeof(TModel).GetProperties(); List<string> list = new List<string>(); string key = PrimaryKey; if (props != null && props.Length > 0) { foreach (PropertyInfo prop in props) { if (prop.GetValue(model, null) != null && !prop.Name.Equals(key, StringComparison.OrdinalIgnoreCase)) { list.Add(prop.Name); } } } return list.ToArray(); } #endregion } }
代碼中的TableInfoAttribute類是我建一個(gè)屬性特性類,用于標(biāo)識(shí)表名和主鍵名稱的特性類,假如Entity實(shí)體類上面沒有標(biāo)識(shí)主鍵名稱,框架默認(rèn)會(huì)用Entity類名作為表名,建議***標(biāo)識(shí)一下表名和主鍵名稱。
NetUtility.Dapper.Core.TableInfoAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetUtility.Dapper.Core { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] /// <summary> /// 標(biāo)識(shí)表名、主鍵等信息特性類 /// </summary> public class TableInfoAttribute : Attribute { /// <summary> /// 數(shù)據(jù)庫(kù)表名 /// </summary> public string TableName { get; set; } /// <summary> /// 主鍵名稱 /// </summary> public string PrimaryKey { get; set; } public TableInfoAttribute() { } public TableInfoAttribute(string tableName, string key) { this.TableName = tableName; this.PrimaryKey = key; } } }using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetUtility.Dapper.Core { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] /// <summary> /// 標(biāo)識(shí)表名、主鍵等信息特性類 /// </summary> public class TableInfoAttribute : Attribute { /// <summary> /// 數(shù)據(jù)庫(kù)表名 /// </summary> public string TableName { get; set; } /// <summary> /// 主鍵名稱 /// </summary> public string PrimaryKey { get; set; } public TableInfoAttribute() { } public TableInfoAttribute(string tableName, string key) { this.TableName = tableName; this.PrimaryKey = key; } } }
好,下面就是新建一個(gè)抽象類,用于抽象出增刪改查的 ExecuteSql<TModel> 泛型抽象類
NetUtility.Dapper.Core.ExecuteSql.cs
using Dapper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetUtility.Dapper.Core { public abstract class ExecuteSql<TModel> where TModel : class { #region Insert非Null屬性的對(duì)象實(shí)例+Insert(TModel model) /// <summary> /// Insert非Null屬性的對(duì)象實(shí)例 /// </summary> /// <param name="model"></param> /// <returns></returns> public virtual int Insert(TModel model) { string sql = DataMapping<TModel>.GetInsertSql(model); object res = DataBaseAccess.ExecuteScalar(sql, model); if (res != null) { return Convert.ToInt32(res); } return 0; } #endregion #region Select * 查詢+Query() /// <summary> /// Select * 查詢 /// </summary> /// <returns></returns> public virtual List<TModel> Query() { string sql = DataMapping<TModel>.GetQuerySql(); return DataBaseAccess.Query<TModel>(sql); } #endregion #region 帶查詢條件的Select查詢+Query(Func<TModel, bool> selector) /// <summary> /// 帶查詢條件的Select查詢 /// </summary> /// <param name="selector"></param> /// <returns></returns> public virtual List<TModel> Query(Func<TModel, bool> selector) { string sql = DataMapping<TModel>.GetQuerySql(); return DataBaseAccess.Query<TModel>(sql, selector); } #endregion #region 得到一個(gè)對(duì)象的實(shí)例+FirstOrDefault(Func<TModel, bool> selector = null) /// <summary> /// 得到一個(gè)對(duì)象的實(shí)例 /// </summary> /// <param name="selector"></param> /// <returns></returns> public virtual TModel FirstOrDefault(Func<TModel, bool> selector = null) { string sql = DataMapping<TModel>.GetQuerySql(); return DataBaseAccess.FirstOrDefault<TModel>(sql, selector); } #endregion #region 批量刪除+Delete(string[] IdList) /// <summary> /// 批量刪除 /// </summary> /// <param name="IdList"></param> /// <returns></returns> public virtual int Delete(string[] IdList) { return DataBaseAccess.Execute(DataMapping<TModel>.GetDeleteSql(), new { IdList = IdList }); } #endregion #region Update 一個(gè)非Null屬性的對(duì)象+Update(TModel model) /// <summary> /// Update 一個(gè)非Null屬性的對(duì)象 /// </summary> /// <param name="model"></param> /// <returns></returns> public virtual int Update(TModel model) { return DataBaseAccess.Execute(DataMapping<TModel>.GetUpdateSql(model), model); } #endregion #region 獲取多個(gè)數(shù)據(jù)集+MultyQuery(string sql, object param = null) /// <summary> /// 獲取多個(gè)數(shù)據(jù)集 /// </summary> /// <param name="sql"></param> /// <param name="param"></param> /// <returns></returns> public virtual SqlMapper.GridReader MultyQuery(string sql, object param = null) { return DataBaseAccess.MultyQuery(sql, param); } #endregion } }
ExecuteSql.cs 類中的方法全是 virsual方法,使用者可以重寫他,特別是查詢方法,一定會(huì)被重寫掉。現(xiàn)在NetUtility.Dapper.Core項(xiàng)目中的類全部寫完了,現(xiàn)在 是我業(yè)務(wù)類的引用了,我現(xiàn)在只需要建一個(gè)業(yè)務(wù)類繼承這個(gè)抽象類,這些增刪改查方法全都有了,已經(jīng)不需要寫了!
下面是我的兩個(gè)實(shí)體類,實(shí)體類用TableInfoAttribute特性類標(biāo)識(shí)出了主鍵名稱和表名稱:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NetUtility.Dapper.Core; namespace NetUtility.Entity { [TableInfo(PrimaryKey ="Id",TableName ="Classes")] public class Classes { public int Id { get; set; } public string Name { get; set; } public string Code { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NetUtility.Dapper.Core; namespace NetUtility.Entity { [TableInfo(PrimaryKey = "Id", TableName = "Student")] public class Student { public int Id { get; set; } public string Name { get; set; } public string Code { get; set; } public int? Age { get; set; } public DateTime? JoinDate { get; set; } public int? ClassesId { get; set; } } }
我再新建一個(gè)StudentRepertories業(yè)務(wù)類,繼承ExecuteSql抽象類。
NetUtility.Repertories.StudentRepertories.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NetUtility.Dapper.Core; using NetUtility.Entity; using NetUtility.Entity.ExstendEntity;//這個(gè)是實(shí)體類的擴(kuò)展類,項(xiàng)目中如不需要可移除 using System.Data; using Dapper; namespace NetUtility.Repertories { public class StudentRepertories : ExecuteSql<Student> { public override List<Student> Query() { return base.Query(); } public List<StudentInfo> QueryInfo() { string sql = "select * from Student a left join Classes b on a.ClassesId=b.Id"; using (IDbConnection conn = DataBaseAccess.CreateConnection()) { return conn.Query<StudentInfo, Classes, StudentInfo>(sql, (stu, classes) => { stu.ClassesModel = classes; return stu; }).ToList(); } } } }
好了,現(xiàn)在我們只需要建一個(gè)控制臺(tái)測(cè)試一下有沒有問(wèn)題就是了,親測(cè),木有問(wèn)題。
NetUtility.ConsoleItem
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NetUtility.Repertories; using NetUtility.Entity; namespace NetUtility.ConsoleItem { class Program { static void Main(string[] args) { //業(yè)務(wù)對(duì)象 StudentRepertories stu = new StudentRepertories(); //實(shí)體對(duì)象 var model = new Student(){Age = 100,ClassesId = 1,Code = "3200020021",JoinDate = DateTime.Now,Name = "老徐"}; //新增一個(gè)對(duì)象 int StudentId = stu.Insert(model); var newModel = stu.FirstOrDefault(a => a.Id == StudentId); //Lambda表達(dá)式查詢 var list = stu.Query(a => a.Age == 100); //不帶參數(shù)查詢 var studentInfoList = stu.QueryInfo(); #region 更新 newModel.Code = "1111111111"; newModel.Id = StudentId; stu.Update(newModel); #endregion // 刪除 stu.Delete(new string[] { newModel.Id.ToString() }); Console.ReadKey(); } } }
到此,相信大家對(duì)“C#抽象增刪改怎么實(shí)現(xiàn)”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
本文題目:C#抽象增刪改怎么實(shí)現(xiàn)
本文來(lái)源:http://vcdvsql.cn/article2/podsoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、企業(yè)建站、面包屑導(dǎo)航、企業(yè)網(wǎng)站制作、建站公司、動(dòng)態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)