从零开始搭建SQLSugar仓储:构建高效的.NET数据访问层

发布时间 2023-11-17 10:57:17作者: 期待你我的相遇

导言

在.NET应用程序中,数据访问层扮演着至关重要的角色,而SQLSugar作为一款轻量级的ORM框架,能够简化数据库操作、提高开发效率。本篇博客将带你从零开始,逐步搭建一个基于SQLSugar的仓储(Repository)层,助你构建一个高效可维护的.NET数据访问层。

步骤一:准备工作

首先,确保你的开发环境中已经安装了.NET Core SDK,并创建了一个空白的.NET Core项目。

dotnet new console -n YourProjectName cd YourProjectName

接下来,安装SQLSugar NuGet包。

dotnet add package SqlSugar

步骤二:配置数据库连接

在项目中添加一个appsettings.json文件,用于存储数据库连接字符串。

{ "ConnectionStrings": { "DefaultConnection": "YourConnectionString" } }

然后,在Program.cs中读取配置。

using Microsoft.Extensions.Configuration; class Program { static void Main() { IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); string connectionString = configuration.GetConnectionString("DefaultConnection"); // 初始化SQLSugar SqlSugarClient db = new SqlSugarClient(new ConnectionConfig { ConnectionString = connectionString, DbType = DbType.SqlServer, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }); // TODO: 使用db进行数据库操作 } }

 


步骤三:定义实体类

在项目中创建一个Models文件夹,并添加与数据库表对应的实体类。

[SugarTable("Users")] public class User { [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public int Id { get; set; } public string UserName { get; set; } public string Email { get; set; } }

步骤四:创建仓储类

在项目中创建一个Repositories文件夹,并添加一个通用的仓储接口IRepository.cs

public interface IRepository<T> where T : class, new() { T GetById(int id); List<T> GetAll(); void Insert(T entity); void Update(T entity); void Delete(T entity); }

然后,实现该接口的SQLSugar仓储类SqlSugarRepository.cs

public class SqlSugarRepository<T> : IRepository<T> where T : class, new() {
private readonly SqlSugarClient _db; public SqlSugarRepository(SqlSugarClient db) { _db = db; } public T GetById(int id) { return _db.Queryable<T>().InSingle(id); } public List<T> GetAll() { return _db.Queryable<T>().ToList(); } public void Insert(T entity) { _db.Insertable(entity).ExecuteCommand(); } public void Update(T entity) { _db.Updateable(entity).ExecuteCommand(); } public void Delete(T entity) { _db.Deleteable(entity).ExecuteCommand(); } }

步骤五:使用仓储进行数据库操作

Program.cs中实例化SqlSugarRepository,并进行数据库操作。

class Program { static void Main() { // ... 省略前面的代码 IRepository<User> userRepository = new SqlSugarRepository<User>(db); // 插入操作 var newUser = new User { UserName = "JohnDoe", Email = "john@example.com" }; userRepository.Insert(newUser); // 查询操作 var user = userRepository.GetById(newUser.Id); Console.WriteLine($"User: {user.UserName}, Email: {user.Email}"); // 更新操作 user.Email = "john.doe@example.com"; userRepository.Update(user); // 删除操作 userRepository.Delete(user); } }

结语

通过以上步骤,你成功搭建了一个基于SQLSugar的仓储层,实现了简单的数据库操作。在实际项目中,你可以根据需求扩展仓储接口和实现类,使其更符合业务逻辑。希望这篇博客对你构建高效的.NET数据访问层有所帮助!