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
{ /// <summary>
/// 获取所有用户数据
/// </summary>
[HttpGet] public List<Users> GetUsers(GetUserInput input){
//分页数据
List<Users> users = new List<Users>();
using(IDbConnection connection=DapperContext.Connection()){ users = connection.Query<Users>("select * from user limit @PageIndex,@PageSize",new {
PageIndex=input.PageIndex*input.PageSize,
PageSize=input.PageSize
}).ToList();
}
return users; } /// <summary>
/// 根据用户ID 查询
/// </summary>
[HttpGet("{id}")]
public Users Get(int id)
{
using(IDbConnection connection=DapperContext.Connection()){ return connection.Query<Users>("select * from user where id=@Id",new {@Id=id}).FirstOrDefault();
}
} /// <summary>
/// 插入数据
/// </summary>
[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 });
}
} /// <summary>
/// 修改数据
/// </summary>
[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 });
}
} /// <summary>
/// 删除数据
/// </summary>
[HttpDelete("{id}")]
public void Delete(int id)
{
using(IDbConnection connection=DapperContext.Connection()){
connection.Execute("delete from user where id=@Id", new { Id = id });
}
}
}
只是简单的使用Dapper,如需更多了解建议查看官方文档。