IN 操作符允许我们在 WHERE 子句中规定多个值。
本篇文章中,还是使用和上篇文章中同样的实体类和数据库,Dapper使用in操作符的代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Configuration; 7 using Dapper; 8 using System.Data.SqlClient; 9 using System.Data; 10 using DapperApplicationByIn.Model; 11 12 namespace DapperApplicationByIn 13 { 14 class Program 15 { 16 static void Main(string[] args) 17 { 18 // 定义连接字符串 19 string conn = ConfigurationManager.ConnectionStrings["AppConnection"].ConnectionString; 20 21 #region in查询 22 using (IDbConnection connection = new SqlConnection(conn)) 23 { 24 var sql = "select * from Users where Email in @emails"; 25 var result = connection.Query<User>(sql, new { emails = new string[2] { "fqy@qq.com", "hyj@163.com" } }); 26 result.AsList().ForEach(p => 27 { 28 Console.WriteLine("Id:"+p.UserId+" UserName:"+p.UserName+" Email:"+p.Email+" Address:"+p.Address); 29 }); 30 } 31 #endregion 32 33 Console.ReadKey(); 34 } 35 } 36 }
程序运行结果:
示例代码下载地址:https://pan.baidu.com/s/1o7RokDs