欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.net mvc + Dapper 实例

程序员文章站 2024-02-27 19:26:09
...

简介

此文章为.net mvc + Dapper学习实例,文后有实例源码链接。

为什么写这篇文章

因不喜欢EF的臃肿和Linq的别扭,以往项目中采用自己弄的轻量级ORM,在思考和借鉴其他ORM框架中,
发现Dapper。Dapper的介绍度娘一堆,这里就不介绍了。

话不多说,看随笔

  1. 创建MVC项目
    .net mvc + Dapper 实例
  2. 通过Nuget获取Dapper
    .net mvc + Dapper 实例
    搜索Dapper,并安装,先测试Dapper,过后再测试SimpleCRUD
    .net mvc + Dapper 实例
    Dapper对.net Framework 版本有限定,所以搭建的项目一定要注意,我创建的项目为 4.5.1。
    .net mvc + Dapper 实例
    .net mvc + Dapper 实例
  3. 代码
  • 数据库
	/***表***/
	CREATE TABLE Users
	(
		Id INT PRIMARY KEY IDENTITY(1,1),
		UserName NVARCHAR(20),
		UserPWD NVARCHAR(32),
		NickName NVARCHAR(20),
		UserStatus int,
		LastLoginOn DATETIME
	)
	GO
	/************************
	普通的存储过程
	*************************/
	CREATE PROC proc_GetUsers
	AS
	BEGIN
		SELECT * FROM Users;
	END
	GO
 	/**************************
    带参数的存储过程
    ***************************/
    CREATE PROC proc_GetUsers_OutParam
    (
    	@Id INT,
    	@UserName NVARCHAR(20) output
    )
    AS
    BEGIN
    	SELECT @UserName=UserName FROM Users WHERE aaa@qq.com;
    END
  • 实体层
    在Model层中创建Users类
	public class Users
    {
        /// <summary>
        /// 主键 自增
        /// </summary>
        public int? Id { get; set; }
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string UserPWD { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string NickName { get; set; }
        /// <summary>
        /// 状态
        /// </summary>
        public int? UserStatus { get; set; }
        /// <summary>
        /// 最后登陆时间
        /// </summary>
        public DateTime? LastLoginOn { get; set; }
    }

  • 服务层
/// <summary>
    /// 用户服务
    /// Dapper框架的服务
    /// </summary>
    public class Users_Biz
    {
        const string connstr = "Data Source=.;Initial Catalog=DBTest;User Id=sa;Password=123456;";
        //private readonly string connstr =
        //         "Data Source=.;Initial Catalog=DBTest;User Id=sa;Password=123456;";
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model">用户对象</param>
        public static int Add(Users model)
        {
            int count = 0;
           
            using (IDbConnection conn=new SqlConnection(connstr))
            {
                string sql = "insert into Users(UserName,UserPWD,NickName,UserStatus,LastLoginOn) values(@UserName,@UserPWD,@NickName,@UserStatus,@LastLoginOn)";
                count =conn.Execute(sql, new { UserName = model.UserName, UserPWD = model.UserPWD, NickName = model.NickName, model.UserStatus, model.LastLoginOn });
            }
            return count;
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public static List<Users> GetList()
        {
            List<Users> list = null;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                string sql = "select * from Users";
                list = conn.Query<Users>(sql).ToList();
            }
            return list;
        }
        /// <summary>
        /// 通过Id查找
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Users GetModel(int id)
        {
            Users model = null;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                string sql = "select * from Users where aaa@qq.com";
                model = conn.QueryFirstOrDefault<Users>(sql, new { Id = id });
            }
            return model;
        }
        /// <summary>
        /// 查找最后一个
        /// </summary>
        /// <returns></returns>
        public static Users GetLastModel()
        {
            Users model = null;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                string sql = "select * from Users order by Id desc";
                model = conn.QueryFirstOrDefault<Users>(sql);
            }
            return model;
        }
        /// <summary>
        /// 查询总行数
        /// </summary>
        /// <returns></returns>
        public static int GetCount()
        {
            int count = 0;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                string sql = "select count(1) from Users";
                count = (int)conn.ExecuteScalar(sql);
            }

            return count;
        }
        /// <summary>
        /// 查询List
        /// 调用普通存储过程
        /// </summary>
        /// <returns></returns>
        public static List<Users> GetList_Proc()
        {
            List<Users> list = null;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                list = conn.Query<Users>("proc_GetUsers", null, null, true,null, CommandType.StoredProcedure).ToList();
            }
            return list;
        }

        /// <summary>
        /// 通过Id查询UserName
        /// 带返回参数的存储过程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetUserName_Proc(int id)
        {
            int count = 0;
            string userName = string.Empty ;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                //设置参数集合
                DynamicParameters dp = new DynamicParameters();
                dp.Add("@Id", id);
                dp.Add("@UserName", userName, DbType.String, ParameterDirection.Output);
                //执行出差过程
                count = conn.Execute("proc_GetUsers_OutParam", dp, null, null, CommandType.StoredProcedure);
                //获取参数
                userName = dp.Get<string>("@UserName");
            }
            return userName;

        }
    }
  • 控制器层
 public ActionResult Index()
        {
            //1 新增
            Users model = new Users()
            {
                UserName = "Seven",
                UserPWD = "13333",
                NickName = "赛文",
                UserStatus = 1,
                LastLoginOn = DateTime.Now
            };
            int addRes = Users_Biz.Add(model);

            //2 查询列表
           List<Users> list= Users_Biz.GetList();
            //3 通过Id查询
            model = Users_Biz.GetModel(1);
            //4 新增
            model.UserName = "Eleven";
            model.UserPWD = "88886666";
            model.NickName = "伊莱文";
            addRes = Users_Biz.Add(model);
            //5 查询最后一个
            model = Users_Biz.GetLastModel();
            //6 查找总个数
            int count = Users_Biz.GetCount();
            //7 调用普通存储过程
            list = Users_Biz.GetList_Proc();
            //8 调用带返回参数的存储过程
            string userName = Users_Biz.GetUserName_Proc(1);
           string json= JsonConvert.SerializeObject(new {
                新增1=addRes,
                查询列表=list,
                通过Id查询=model,
                查找总数=count,
                调用带返回参数的存储过程=userName
            });
            return Content(json);
        }

至此,Dapper基本的操作已经做完,看上去还是比较简单的。
但是我们会发现一个,这个是需要写SQL语句的,这种感觉很不爽。
想要通过反射的方式来进行SQL的自动拼接,便可以实现不写SQL就能完成实体操作了。
在Nuget中,***Dapper.SimpleCRUD***便是这样的一个类库。

.net mvc + Dapper 实例
我们再写一遍服务类:

 public class Users_BizEx
    {
        const string connstr = "Data Source=.;Initial Catalog=DBTest;User Id=sa;Password=123456;";
        //private readonly string connstr =
        //         "Data Source=.;Initial Catalog=DBTest;User Id=sa;Password=123456;";
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model">用户对象</param>
        public static int Add(Users model)
        {
            int? count = 0;

            using (IDbConnection conn = new SqlConnection(connstr))
            {
                count = conn.Insert<Users>(model);
              
            }
            return count.Value;
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public static List<Users> GetList()
        {
            List<Users> list = null;
            using (IDbConnection conn = new SqlConnection(connstr))
            {

                list = conn.GetList<Users>().ToList();
            }
            return list;
        }
        /// <summary>
        /// 通过Id查找
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Users GetModel(int id)
        {
            Users model = null;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                model = conn.Get<Users>(id);
            }
            return model;
        }
        /// <summary>
        /// 查找最后一个(分页查询)
        /// </summary>
        /// <returns></returns>
        public static Users GetLastModel()
        {
            Users model = null;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                model = conn.GetListPaged<Users>(1, 1, string.Empty, "Id desc").ToList().FirstOrDefault();
            }
            return model;
        }
        /// <summary>
        /// 查询总行数
        /// </summary>
        /// <returns></returns>
        public static int GetCount()
        {
            int count = 0;
            using (IDbConnection conn = new SqlConnection(connstr))
            {

                count = conn.RecordCount<Users>(string.Empty);
            }

            return count;
        }
        /// <summary>
        /// 查询List
        /// 调用普通存储过程
        /// </summary>
        /// <returns></returns>
        public static List<Users> GetList_Proc()
        {
            List<Users> list = null;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                list = conn.Query<Users>("proc_GetUsers", null, null, true, null, CommandType.StoredProcedure).ToList();
            }
            return list;
        }

        /// <summary>
        /// 通过Id查询UserName
        /// 带返回参数的存储过程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetUserName_Proc(int id)
        {
            int count = 0;
            string userName = string.Empty;
            using (IDbConnection conn = new SqlConnection(connstr))
            {
                //设置参数集合
                DynamicParameters dp = new DynamicParameters();
                dp.Add("@Id", id);
                dp.Add("@UserName", userName, DbType.String, ParameterDirection.Output);
                //执行出差过程
                count = conn.Execute("proc_GetUsers_OutParam", dp, null, null, CommandType.StoredProcedure);
                //获取参数
                userName = dp.Get<string>("@UserName");
            }
            return userName;

        }
    }

总结

Dapper这个轻量级的ORM还是不错的,如果对这个类库的源码感兴趣,可以去git一下。

项目源码

百度网盘
链接:https://pan.baidu.com/s/1KIqZHjLYtU1oiIUgWysyjw
提取码:8tjj