.net core Dapper for MySql

Dapper 语法比较简单,效率也比较快,速度接近IDataReader 甚至读取数据超过了DataTable,建议在实际项目可以结合EntityFramework Core 一起使用。

一、创建MySql Table 

CREATE TABLE User (
  Id int(11) NOT NULL AUTO_INCREMENT,
  Name varchar(255) DEFAULT NULL,
  PRIMARY KEY (Id)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

二、创建Model

 public class Users
 {
    public int Id { get; set; }
    public string Name { get; set; }
 }

三、Dapper Helper

 public  class DapperContext
    {    
//连接字符串
const string connectionString = "Server=localhost;port=3306;Database=testDB;Uid=root;Pwd=123abc;SslMode=None;"; public static MySqlConnection Connection(){ var mysql=new MySqlConnection(connectionString); mysql.Open(); return mysql; } }

四、WEBAPI 

 [Route("api/[controller]")]
    public class UserController : Controller
    {
            

        /// 
        /// 获取所有用户数据
        /// 
        [HttpGet]

        public List GetUsers(GetUserInput input){
           //分页数据
            List users = new List();         
            using(IDbConnection connection=DapperContext.Connection()){
            
                users = connection.Query("select * from user limit @PageIndex,@PageSize",new {
                    PageIndex=input.PageIndex*input.PageSize,
                    PageSize=input.PageSize
                }).ToList();
            }
            return users;
         
        }

        /// 
        /// 根据用户ID 查询
        /// 
        [HttpGet("{id}")]
        public Users Get(int id)
        {
            using(IDbConnection connection=DapperContext.Connection()){

                return connection.Query("select * from user where id=@Id",new {@Id=id}).FirstOrDefault();
            }
        }

        /// 
        /// 插入数据
        /// 
        [HttpPost]
        public void Post([FromBody]Users value)
        {
            using(IDbConnection connection=DapperContext.Connection()){
                connection.Execute("insert into user values(@Id,@Name)", new { value.Id,value.Name });
            }
        }
        
       /// 
       /// 修改数据
       /// 
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)      
        {
            using(IDbConnection connection=DapperContext.Connection()){

                connection.Execute("update user set name=@Name where id=@Id", new { Id = id, Name = value });
            }
        }

        /// 
        /// 删除数据
        /// 
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            using(IDbConnection connection=DapperContext.Connection()){
                connection.Execute("delete from user where id=@Id", new { Id = id });
            }
        }
    }

只是简单的使用Dapper,如需更多了解建议查看官方文档。

你可能感兴趣的:(.net core Dapper for MySql)