Dapper框架
1.项目引用Dapper的Nuget程序包;
2.配置链接类
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dapper { public class DapperConn { public static IDbConnection GetConnection() { string connStr = ConfigurationManager.AppSettings["conn"]; return new SqlConnection(connStr); } } }
3.配置相应表的实体对象
目前是一个用户表和一个用户登录日志表为例:
用户表
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dapper { public class UserModel { public Int32 Id { get; set; } public String Key { get; set; } public String Value { get; set; } } }
用户登录日志表
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dapper { public class UserLoginLog { public Int32 Id { get; set; } public Int32 UserId { get; set; } public DateTime CreateTime { get; set; } } }
4.通过实体对数据库操作
(包含基本的:增删改查及事务提交操作)
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dapper { public class DB { public int Add(UserModel model) { using (var conn = DapperConn.GetConnection()) { string sql = "Insert into User (Key,Value) Value (@Key,@Value)"; return conn.Execute(sql, model); } } public int Update(UserModel model) { using (var conn = DapperConn.GetConnection()) { string sql = "update User set [email protected],[email protected] where [email protected]"; return conn.Execute(sql, model); } } public int Del(UserModel model) { using (var conn = DapperConn.GetConnection()) { string sql = "Delete from User where [email protected]"; return conn.Execute(sql, model); } } public UserModel GetModel() { using (var conn = DapperConn.GetConnection()) { var sql = "Select Id,Key,Value from User"; return conn.QueryFirstOrDefault<UserModel>(sql); } } public IEnumerable<UserModel> GetModels() { using (var conn = DapperConn.GetConnection()) { var sql = "Select Id,Key,Value from User"; return conn.Query<UserModel>(sql); } } public void ImplementAffair(UserModel userModel, UserLoginLog userLogModel) { using (var conn = DapperConn.GetConnection()) { IDbTransaction tran = conn.BeginTransaction(); try { string query = "Update User set Key=‘测试‘ where [email protected]";//更新一条记录 conn.Execute(query, userModel, tran, null, null); query = "insert into UserLoginLog (userId,CreateTime) value (@userId,@CreateTime)";//删除一条记录 conn.Execute(query, userLogModel, tran, null, null); //提交 tran.Commit(); } catch (Exception ex) { //提交错误 //回滚事务 tran.Rollback(); } } } } }
时间: 2024-10-29 19:08:57