前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Dapper连接与事务的简单封装

Dapper连接与事务的简单封装

作者头像
潘成涛
发布2018-07-09 16:47:05
9400
发布2018-07-09 16:47:05
举报
文章被收录于专栏:程序员与猫

增删改查方面,已经有Dapper.Extension这么强大的工具了,我也实在没啥好写的,就随手写了个看起来比较优雅的连接与事务的封装。在之后使用Dapper.Extension类库时,完全可以照搬进去。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using DapperDemo.Models;

namespace DapperDemo
{
    internal class Program
    {
        public static string ConnString = "Server=(localdb)\\MSSQLLocalDB;Database=DapperDB;";

        private static void Main(string[] args)
        {
            BuckInsert();
            BuckInsert();
            BuckInsert();
            DeleteAfterUpdating();
            GetPersonList().ForEach(c=>Console.WriteLine(c.UserName));
        }

        public static List<Person> GetPersonList()
        {
            var people = new List<Person>();

            ExecuteWithoutTransaction(conn =>
            {
                people = conn.Query<Person>("select * from Person where id>@id", new {id = 2}).ToList();
            });

            return people;
        }

        public static bool BuckInsert()
        {
            return ExecuteWithTransaction((conn, trans) =>
            {
                var r = conn.Execute(
                    @"insert Person(username, password,age,registerDate,address) values (@a, @b,@c,@d,@e)",
                    new[]
                    {
                        new {a = 1, b = 1, c = 1, d = DateTime.Now, e = 1},
                        new {a = 2, b = 2, c = 2, d = DateTime.Now, e = 2},
                        new {a = 3, b = 3, c = 3, d = DateTime.Now, e = 3}
                    },trans);

                return r;
            });
        }

        public static bool Update()
        {
            return ExecuteWithTransaction((conn, trans) =>
            {
                var r = conn.Execute(@"update Person set password='www.lanhuseo.com' where username=@username",
                    new {username = 2}, trans);

                return r;
            });
        }

        public static bool Delete()
        {
            return ExecuteWithTransaction((conn, trans) =>
            {
                var r = conn.Execute(@"delete from Person where id=@id", new {id = 1009}, trans);

                return r;
            });
        }

        public static bool DeleteAfterUpdating()
        {
            return ExecuteWithTransaction((conn, trans) =>
            {
                var r = conn.Execute(@"update Person set password='www.lanhuseo.com' where id=@id", new {id = 1009}, trans,
                    null, null);
                r += conn.Execute("delete from Person where id=@id", new {id = 1010}, trans, null, null);

                return r;
            });
        }

        /// <summary>
        ///     Used for query
        /// </summary>
        /// <param name="action"></param>
        public static void ExecuteWithoutTransaction(Action<SqlConnection> action)
        {
            UseConnectObj(action);
        }

        /// <summary>
        ///     Used for cud
        /// </summary>
        /// <returns>Execute Result</returns>
        /// <param name="func"></param>
        public static bool ExecuteWithTransaction(Func<SqlConnection, IDbTransaction, int> func)
        {
            var r = 0;

            UseConnectObj(conn =>
            {
                IDbTransaction trans = conn.BeginTransaction();

                r = func(conn, trans);

                trans.Commit();
            });

            return r > 0;
        }

        /// <summary>
        ///     Use Action Connection
        /// </summary>
        /// <param name="action"></param>
        public static void UseConnectObj(Action<SqlConnection> action)
        {
            using (var conn = new SqlConnection(ConnString))
            {
                conn.Open();
                action(conn);
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-05-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档