using System.Collections.Generic; using System.Threading.Tasks; using MDL.Models; using DAL.Interfaces; using DB.Database; using SqlSugar; namespace DAL.Repositories { /// /// 客户资料的数据访问实现类 /// public class CustomerRepository : ICustomerRepository { private readonly ISqlSugarProvider _provider; /// /// 构造函数 /// /// SqlSugar数据库提供程序 public CustomerRepository(ISqlSugarProvider provider) { _provider = provider; } /// /// 创建客户记录 /// /// 客户实体 /// 创建的记录ID public async Task CreateAsync(CustomerEntity entity) { var db = _provider.GetClient(); // 确保表存在 if (!db.DbMaintenance.IsAnyTable("customers")) { db.CodeFirst.InitTables(typeof(CustomerEntity)); } // 设置时间戳 entity.CreatedAt = DateTime.UtcNow; entity.UpdatedAt = DateTime.UtcNow; // 插入数据并返回自增ID return await db.Insertable(entity).ExecuteReturnIdentityAsync(); } /// /// 根据ID获取客户记录 /// /// 记录ID /// 客户实体 public async Task GetByIdAsync(int id) { var db = _provider.GetClient(); return await db.Queryable() .Where(x => x.Id == id) .FirstAsync(); } /// /// 根据客户代码获取客户记录 /// /// 客户代码 /// 客户实体 public async Task GetByCustomerCodeAsync(string customerCode) { var db = _provider.GetClient(); return await db.Queryable() .Where(x => x.CustomerCode == customerCode) .FirstAsync(); } /// /// 更新客户记录 /// /// 客户实体 /// 更新是否成功 public async Task UpdateAsync(CustomerEntity entity) { var db = _provider.GetClient(); // 更新时间戳 entity.UpdatedAt = DateTime.UtcNow; // 更新数据并返回影响行数 var rows = await db.Updateable(entity).ExecuteCommandAsync(); return rows > 0; } /// /// 删除客户记录 /// /// 记录ID /// 删除是否成功 public async Task DeleteAsync(int id) { var db = _provider.GetClient(); var rows = await db.Deleteable() .Where(x => x.Id == id) .ExecuteCommandAsync(); return rows > 0; } /// /// 获取所有客户记录 /// /// 客户实体列表 public async Task> GetAllAsync() { var db = _provider.GetClient(); return await db.Queryable() .OrderByDescending(x => x.CreatedAt) .ToListAsync(); } /// /// 检查客户是否存在 /// /// 客户代码 /// 是否存在 public async Task ExistsAsync(string customerCode) { var db = _provider.GetClient(); return await db.Queryable() .Where(x => x.CustomerCode == customerCode) .AnyAsync(); } public async Task> GetByIdsAsync(List ids) { if (ids == null || ids.Count == 0) return new List(); var db = _provider.GetClient(); return await db.Queryable() .Where(x => ids.Contains(x.Id)) .ToListAsync(); } } }