欢子 2019-06-26
大家好,
我是Rector,一位专注.NET开发者社区建设的.Neter。我之前推出了一个关于《C#视频教程之使用Dapper轻松访问SQL Server数据库》的系列视频讲座。
这个讲座主要面向的对象是C#的初学者或有意愿了解Dapper的小伙伴们,其中涉及到了:
本文将为大家提供视频中涉及到的核心源码。
在Winform程序的配置文件中,我们需要对数据库连接进行配置,具体的数据库连接字符串配置如下:
App.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" /> </startup> <connectionStrings> <add name="DbConn" connectionString="Server=.\SQLEXPRESS;Database=SampleData;User Id=sa;Password=123456"/> </connectionStrings> </configuration>
数据库连接帮助类是帮助我们从配置文件中读取数据库的连接字符串的,其中包含了一个静态的返回类型为 string
的属性,通过这个属性,我们可以获取到当前应用程序配置的数据库连接字符串,具体代码如下:
DbHelper.cs
using System.Configuration; namespace DapperDemo { /// <summary> /// 数据库连接帮助类 /// </summary> public class DbHelper { /// <summary> /// 从配置文件中读取数据库连接字符串 /// </summary> public static string ConnctionString { get { return ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString; } } } }
用户实体类:本次示例程序中涉及到的用户类,包含了用户的一些基本信息,具体如下:
Person.cs
using System; namespace DapperDemo { /// <summary> /// 用户信息实体类 /// </summary> public class Person { /// <summary> /// 自增ID /// </summary> public int Id { get; set; } /// <summary> /// 名字 /// </summary> public string FirstName { get; set; } /// <summary> /// 姓氏 /// </summary> public string LastName { get; set; } /// <summary> /// 电子邮箱 /// </summary> public string EmailAddress { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreatedOn { get; set; } /// <summary> /// IP地址 /// </summary> public string IpAddress { get; set; } /// <summary> /// 计算属性,返回用户的详细 /// </summary> public string Display { get { return $"{FirstName} {LastName} ({EmailAddress}) {IpAddress}"; } } } }
用户信息服务类:主要负责使用Dapper与数据库进行交互,其中包含的操作有简单的数据增、删、改、查等,具体的实现代码如下:
PersonService.cs
using Dapper; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; namespace DapperDemo { /// <summary> /// 用户信息服务类 /// </summary> public class PersonService { /// <summary> /// 根据用户姓氏查询用户集合 /// </summary> /// <param name="lastName">姓氏</param> /// <returns></returns> public List<Person> FindListByLastName(string lastName) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = $"SELECT * FROM Person WHERE LastName=@LastName"; IEnumerable<Person> list = db.Query<Person>(sql, new { LastName = lastName }); return list.ToList(); } } /// <summary> /// 写入用户信息 /// </summary> /// <param name="person">用户实体</param> /// <returns></returns> public bool Insert(Person person) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = "INSERT INTO Person (FirstName,LastName,EmailAddress) VALUES (@FirstName,@LastName,@EmailAddress)"; int result = db.Execute(sql, person); return result > 0; } } /// <summary> /// 根据用户ID查询用户信息 /// </summary> /// <param name="personId">用户ID</param> /// <returns></returns> public Person FindById(int personId) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = "SELECT * FROM Person WHERE Id=@Id"; IEnumerable<Person> list = db.Query<Person>(sql, new { Id = personId }); return list.FirstOrDefault(); } } /// <summary> /// 更新用户信息 /// </summary> /// <param name="person">用户实体</param> /// <returns></returns> public bool Update(Person person) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = "UPDATE Person SET FirstName=@FirstName,LastName=@LastName,EmailAddress=@EmailAddress WHERE Id=@Id"; int result = db.Execute(sql, person); return result > 0; } } /// <summary> /// 删除用户信息 /// </summary> /// <param name="personId">用户ID</param> /// <returns></returns> public bool Delete(int personId) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = "DELETE FROM Person WHERE Id=@Id"; int result = db.Execute(sql, new { Id = personId }); return result > 0; } } } }
最后,是我们的仪表盘后端代码,包含了示例中涉及中的增、删、改、查等事件对应的方法实现,如下:
Dashboard.cs
using System; using System.Collections.Generic; using System.Windows.Forms; namespace DapperDemo { public partial class Dashboard : Form { public Dashboard() { InitializeComponent(); } private void btnSearch_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); List<Person> result = ps.FindListByLastName(txtSearchLastName.Text); lstSearchResult.DataSource = result; lstSearchResult.DisplayMember = "Display"; } private void btnCreate_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); //person.FirstName = txtFrmFirstName.Text; //person.LastName = txtFrmLastName.Text; //person.EmailAddress = txtFrmEmailAddress.Text; Person person = new Person { FirstName = txtFrmFirstName.Text, LastName = txtFrmLastName.Text, EmailAddress = txtFrmEmailAddress.Text }; bool success = ps.Insert(person); MessageBox.Show(success ? "操作成功" : "操作失败"); } private void btnIndex_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); int personId = Convert.ToInt32(txtIndexPersonId.Text); Person person = ps.FindById(personId); txtFrmFirstName.Text = person.FirstName; txtFrmLastName.Text = person.LastName; txtFrmEmailAddress.Text = person.EmailAddress; } private void btnUpdate_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); Person person = new Person { Id = Convert.ToInt32(txtIndexPersonId.Text), FirstName = txtFrmFirstName.Text, LastName = txtFrmLastName.Text, EmailAddress = txtFrmEmailAddress.Text }; bool success = ps.Update(person); MessageBox.Show(success ? "操作成功" : "操作失败"); } private void btnDelete_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); int personId = Convert.ToInt32(txtIndexPersonId.Text); bool success = ps.Delete(personId); MessageBox.Show(success ? "操作成功" : "操作失败"); } } }
视频教程中分享的两个网址:
希望对大家有所帮助,谢谢。
如果有学习过程中遇到任何问题,请加我们的.NET开发者社区学习交流群:483350228