本篇內(nèi)容主要講解“C#抽象增刪改怎么實(shí)現(xiàn)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“C#抽象增刪改怎么實(shí)現(xiàn)”吧!
10年積累的成都網(wǎng)站建設(shè)、成都做網(wǎng)站經(jīng)驗(yàn),可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有臨澤免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
現(xiàn)在業(yè)界火了一種ORM 框架,那就是Dapper,我也是Dapper的粉絲之一,而我總結(jié)出來的框架也是基于Daaper。下面是我的代碼,首先是Dapper Helper類,數(shù)據(jù)庫通用訪問類(用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
{
///
/// 數(shù)據(jù)庫訪問類
///
public class DataBaseAccess
{
public static SqlConnection CreateConnection()
{
string connStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
return conn;
}
///
/// 執(zhí)行增、刪、改方法
///
///
///
///
public static int Execute(string sql, object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.Execute(sql,parms);
}
}
///
/// 得到單行單列
///
///
///
///
public static object ExecuteScalar(string sql, object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.ExecuteScalar(sql, parms);
}
}
///
/// 單個(gè)數(shù)據(jù)集查詢
///
///
///
///
public static List
Query (string sql,Func pre ,object parms = null) {
using (IDbConnection conn = CreateConnection())
{
return conn.Query
(sql, parms).Where(pre).ToList(); }
}
///
/// 單個(gè)數(shù)據(jù)集查詢
///
///
///
///
public static List
Query (string sql, object parms = null) {
using (IDbConnection conn = CreateConnection())
{
return conn.Query
(sql, parms).ToList(); }
}
///
/// 多個(gè)數(shù)據(jù)集查詢
///
///
///
///
public static SqlMapper.GridReader MultyQuery(string sql, object parms = null)
{
using (IDbConnection conn = CreateConnection())
{
return conn.QueryMultiple(sql, parms);
}
}
///
/// 單個(gè)數(shù)據(jù)集查詢
///
///
///
///
public static TEntity FirstOrDefault
(string sql,Func selector, object parms = null) {
using (IDbConnection conn = CreateConnection())
{
return conn.Query
(sql, parms).Where(selector).FirstOrDefault(); }
}
}
}
我把增刪改查抽象出來了,少不了的就是SQL語句的生成,生成SQL語句,要么是映射,要么是反射,而我用的是反射,給一個(gè)Entity類,我讀取他所有屬性和字段,然后生成對應(yīng)的SQL語句。 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 DataMappingwhere TModel : class { #region 數(shù)據(jù)庫類型+DataBaseType /// /// 數(shù)據(jù)庫類型 /// public static string DataBaseType { get { string strType = ConfigurationManager.AppSettings["DataBaseType"]; if (!string.IsNullOrEmpty(strType)) { return strType; } else { return string.Empty; } } } #endregion #region 主鍵屬性字段+PrimaryKey ////// 主鍵字段名稱 /// public static string PrimaryKey { get { Type t = typeof(TModel); TableInfoAttribute tableInfo = t.GetCustomAttribute(typeof(TableInfoAttribute), true) as TableInfoAttribute; if (tableInfo!=null)//如果沒有標(biāo)識表信息特性,則通過表名向數(shù)據(jù)庫中得到主鍵信息 { 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 ////// 獲取表名 /// /// 數(shù)據(jù)庫表名前綴 ///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 查詢語句+GetQuerySql /// /// Select 查詢語句 /// ///public static string GetQuerySql() { StringBuilder sql = new StringBuilder("select * from "); sql.Append(TableName()); return sql.ToString(); } #endregion #region Insert非Null屬性的對象實(shí)例 Sql 語句+GetInsertSql /// /// Insert 非Null屬性的對象實(shí)例 Sql 語句 /// /// ///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 語句+GetDeleteSql /// /// Delete Sql 語句 /// ///public static string GetDeleteSql() { return string.Format(@"delete from {0} where {1} in @IdList", TableName(), PrimaryKey); } #endregion #region Update 非Null屬性的對象實(shí)例 Sql語句+GetUpdateSql /// /// Update 非Null屬性的對象實(shí)例 Sql語句 /// /// ///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 /// /// 非主鍵且非Null屬性 /// /// ///public static string[] Propertys(TModel model) { PropertyInfo[] props = typeof(TModel).GetProperties(); List list = new List (); 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)識表名和主鍵名稱的特性類,假如Entity實(shí)體類上面沒有標(biāo)識主鍵名稱,框架默認(rèn)會用Entity類名作為表名,建議***標(biāo)識一下表名和主鍵名稱。
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)] ////// 標(biāo)識表名、主鍵等信息特性類 /// public class TableInfoAttribute : Attribute { ////// 數(shù)據(jù)庫表名 /// public string TableName { get; set; } ////// 主鍵名稱 /// 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)] ////// 標(biāo)識表名、主鍵等信息特性類 /// public class TableInfoAttribute : Attribute { ////// 數(shù)據(jù)庫表名 /// public string TableName { get; set; } ////// 主鍵名稱 /// public string PrimaryKey { get; set; } public TableInfoAttribute() { } public TableInfoAttribute(string tableName, string key) { this.TableName = tableName; this.PrimaryKey = key; } } }
好,下面就是新建一個(gè)抽象類,用于抽象出增刪改查的 ExecuteSql
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 ExecuteSqlwhere TModel : class { #region Insert非Null屬性的對象實(shí)例+Insert(TModel model) /// /// Insert非Null屬性的對象實(shí)例 /// /// ///public virtual int Insert(TModel model) { string sql = DataMapping .GetInsertSql(model); object res = DataBaseAccess.ExecuteScalar(sql, model); if (res != null) { return Convert.ToInt32(res); } return 0; } #endregion #region Select * 查詢+Query() /// /// Select * 查詢 /// ///public virtual List Query() { string sql = DataMapping .GetQuerySql(); return DataBaseAccess.Query (sql); } #endregion #region 帶查詢條件的Select查詢+Query(Func selector) /// /// 帶查詢條件的Select查詢 /// /// ///public virtual List Query(Func selector) { string sql = DataMapping .GetQuerySql(); return DataBaseAccess.Query (sql, selector); } #endregion #region 得到一個(gè)對象的實(shí)例+FirstOrDefault(Func selector = null) /// /// 得到一個(gè)對象的實(shí)例 /// /// ///public virtual TModel FirstOrDefault(Func selector = null) { string sql = DataMapping .GetQuerySql(); return DataBaseAccess.FirstOrDefault (sql, selector); } #endregion #region 批量刪除+Delete(string[] IdList) /// /// 批量刪除 /// /// ///public virtual int Delete(string[] IdList) { return DataBaseAccess.Execute(DataMapping .GetDeleteSql(), new { IdList = IdList }); } #endregion #region Update 一個(gè)非Null屬性的對象+Update(TModel model) /// /// Update 一個(gè)非Null屬性的對象 /// /// ///public virtual int Update(TModel model) { return DataBaseAccess.Execute(DataMapping .GetUpdateSql(model), model); } #endregion #region 獲取多個(gè)數(shù)據(jù)集+MultyQuery(string sql, object param = null) /// /// 獲取多個(gè)數(shù)據(jù)集 /// /// /// ///public virtual SqlMapper.GridReader MultyQuery(string sql, object param = null) { return DataBaseAccess.MultyQuery(sql, param); } #endregion } }
ExecuteSql.cs 類中的方法全是 virsual方法,使用者可以重寫他,特別是查詢方法,一定會被重寫掉?,F(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)識出了主鍵名稱和表名稱:
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{ public override List Query() { return base.Query(); } public List QueryInfo() { string sql = "select * from Student a left join Classes b on a.ClassesId=b.Id"; using (IDbConnection conn = DataBaseAccess.CreateConnection()) { return conn.Query (sql, (stu, classes) => { stu.ClassesModel = classes; return stu; }).ToList(); } } } }
好了,現(xiàn)在我們只需要建一個(gè)控制臺測試一下有沒有問題就是了,親測,木有問題。
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ù)對象 StudentRepertories stu = new StudentRepertories(); //實(shí)體對象 var model = new Student(){Age = 100,ClassesId = 1,Code = "3200020021",JoinDate = DateTime.Now,Name = "老徐"}; //新增一個(gè)對象 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(); } } }
到此,相信大家對“C#抽象增刪改怎么實(shí)現(xiàn)”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!