C# Dapper基本三层架构使用 (三、DAL)
数据访问层(DAL),主要是存放对数据类的访问,即对数据库的添加、删除、修改、更新等基本操作
首先需要在UI层App.Config配置文件中增加连接字符串,如下所示
<connectionStrings> <add name="con" connectionString="Data Source=127.0.0.1;Initial Catalog=Northwind;User ID=sa;Password=*******;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"/> </connectionStrings>
在DAL类库中添加Configuration引用,这样才能访问App.config配置
在DAL类库中添加RegionService.cs类
类库结构如下
添加类库引用
并在项目using中引用以下命名空间
using Dapper; using System.Configuration; using Northwind.Model; using System.Data; using System.Data.SqlClient;
在类中增加访问数据库字符串的静态变量,以供整个类中访问数据库
private static string connStr = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
添加根据RegionID查询数据库中的数据,并返回数据
public static Region GetById(int id) { using (IDbConnection conn = new SqlConnection(connStr)) { string sql = "SELECT r.RegionID, r.RegionDescription FROM Region AS r WHERE "; DynamicParameters parameters = new DynamicParameters(); parameters.Add("RegionID", id); IEnumerable<Region> region = conn.Query<Region>(sql, parameters); return region.FirstOrDefault(); } }
添加数据
public static bool Insert(Region region) { using (IDbConnection conn = new SqlConnection(connStr)) { string sql = @"INSERT INTO Region ( RegionID, RegionDescription ) VALUES ( @RegionID, @RegionDescription )"; DynamicParameters parameters = new DynamicParameters(); parameters.Add("RegionID", region.RegionID); parameters.Add("RegionDescription", region.RegionDescription); return conn.Execute(sql, parameters) > 0; } }
判断数据是否存在
public static bool IfExists(Region region) { using (IDbConnection conn = new SqlConnection(connStr)) { string sql = "SELECT r.RegionID, r.RegionDescription FROM Region AS r WHERE AND r.RegionDescription=RegionDescription"; DynamicParameters parameters = new DynamicParameters(); parameters.Add("RegionID", region.RegionID); parameters.Add("RegionDescription", region.RegionDescription); IEnumerable<Region> regions = conn.Query<Region>(sql, parameters); return regions.Count<Region>() > 0; } }