轻量级ORM框架Dapper应用之实现CURD操作

2022-04-17 09:36:53

在上一篇文章中,讲解了如何安装Dapper,这篇文章中将会讲解如何使用Dapper使用CURD操作。

例子中使用到的实体类定义如下:

using System;using System.Collections.Generic;using System        var query = connection.Query<User>("SELECT * FROM Users");        query.AsList().ForEach(p =>         {              Console.WriteLine("Id:"+p.UserId+" UserName:"+p.UserName+" Email:"+p.Email+" Address:"+p.Address);        });}

程序运行结果:

轻量级ORM框架Dapper应用之实现CURD操作

三、更新数据

1、使用匿名类更新

using (IDbConnection connection = new SqlConnection(conn)){       var result = connection.Execute("update Users set UserName='Tim',Address='上海' where UserId=@UserId", new { UserId = 2 });}

查询数据库:

轻量级ORM框架Dapper应用之实现CURD操作

2、使用实体类更新

using (IDbConnection connection = new SqlConnection(conn)){        User user = new Uswww.easck.comer();        user.UserName = "张无忌";        user.UserId = 1;        var result = connection.Execute("update Users set UserName=@UserName where UserId=@UserId", user);}

查询数据库:

轻量级ORM框架Dapper应用之实现CURD操作

3、使用键值对更新

using (IDbConnection connection = new SqlConnection(conn)){       List<KeyValuePair<string, object>> keys = new List<KeyValuePair<string, object>>();       keys.Add(new KeyValuePair<string, object>("@UserName", "风清扬"));       keys.Add(new KeyValuePair<string, object>("@UserId", 2));       var result = connection.Execute("update Users set UserName=@UserName where UserId=@UserId", keys);}

查询数据库:

轻量级ORM框架Dapper应用之实现CURD操作

四、删除数据

1、使用匿名类删除数据

using (IDbConnection connection = new SqlConnection(conn)){       var result = connection.Execute("delete from Users where UserId=@UserId", new { UserId = 3 });}

2、使用实体类删除数据

using (IDbConnection connection = new SqlConnection(conn)){        User user = new User();        user.UserId = 4;        var result = connection.Execute("delete from Users where UserId=@UserId", user);}

示例程序代码下载地址:点此下载

到此这篇关于使用Dapper实现CURD操作的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。