DotNetCore跨平台~Dapper的使用

回到目录

Dapper作为小型ORM的代表作品被我们应用到了dotnet core的项目中,下面将把自己在项目中使用dapper进行curd操作的过程写一下,后期可能会遇到一些问题,大叔也会在这个系列之中进行完善,希望对各位学生有所帮助!

一 安装nuget的dapper包包

二 在startup中注册dapper仓储,并现时注册数据库类型和数据库连接串,因为在mysql和sqlserver中,它们的连接串是不同的,模块化设计请看大叔这篇文章

DotNetCore跨平台~组件化时代来了

     services.UseLog4Logger(o =>
            {
                o.Log4ConfigFileName = "log4.config";
                o.ProjectName = "test";
            }).UseDapper(o =>
            {
                o.ConnString = "Server=localhost;DataBase=test2;UID=root;Password=root;charset=utf8;port=3306;SslMode=None";
                o.DbType = DbType.MySql;
            }).UseDefaultMQ();

三 进行我们的增删改查的操作,主要把测试中的代码用例复制出来,供大家参考

           //建立链接
            var conn = new MySql.Data.MySqlClient.MySqlConnection(config_config);

            //简单select
            var dt = conn.Query<userinfo>("select * from userinfo where UserName=@username", new
            {
                username = "花样百出@sina.com"
            });

            var dt1 = conn.Query<userinfo>("select * from userinfo where UserName=@username", new
            {
                username = "花样百出@sina.com"
            }).Select(o => new
            {
                name = o.UserName
            });

            //inner join & left join
            var dt2 = conn.Query<userinfo, userlogs, userlogDTO>(
                "select *  from userinfo a " +
                "INNER JOIN  userlogs b on a.Id=b.UserId " +
                "where a.userName=@username", (user, logs) =>
                {
                    return new userlogDTO
                    {
                        Id = user.Id,
                        Name = user.UserName,
                        Content = logs.Content,
                        Time = user.AddTime,
                    };
                }, splitOn: "Id,UserId", param: new { username = "test" });

            //insert
            conn.Execute("insert into userinfo (username,addtime) values (@username,@addtime)", new { username = "zzltest", addtime = DateTime.Now });

            //update
            conn.Execute("update userinfo set username=@newname where username=@oldname", new { oldname = "zzltest", newname = "zzlmodify" });

            //delete
            conn.Execute("delete userinfo where username=@name", new { name = "test" });

本篇文章比较基础,主要面向刚开始使用Dapper的同学!

感谢阅读!

回到目录

posted @ 2017-11-16 10:38 张占岭 阅读(...) 评论(...) 编辑 收藏