C# 搭建一个 基于ISqlSugarClient 三层架构框架 涉及数据库仓储 然后中间又有业务逻辑层 案例

要在C#中搭建基于ISqlSugarClient的三层架构框架,你需要定义数据访问层(DAL)、业务逻辑层(BLL)和表现层(UI)。下面是一个完整的例子,涉及数据库仓储、业务逻辑层,以及依赖注入。这个例子基于ASP.NET Core MVC构建,使用ISqlSugarClient来处理数据访问。这个例子中,我们将使用User作为一个简单的实体来演示三层架构。

数据库实体类

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

数据访问层接口与实现

// 数据访问层接口
public interface IUserRepository
{
    User GetById(int id);
    List<User> GetAll();
    void Add(User user);
    void Update(User user);
    void Delete(int id);
}

// 基础仓储实现
public abstract class BaseRepository<T> where T : class, new()
{
    protected readonly ISqlSugarClient _sqlSugarClient;

    protected BaseRepository(ISqlSugarClient sqlSugarClient)
    {
        _sqlSugarClient = sqlSugarClient;
    }

    public virtual T GetById(int id)
    {
        return _sqlSugarClient.Queryable<T>().InSingle(id);
    }

    public virtual List<T> GetAll()
    {
        return _sqlSugarClient.Queryable<T>().ToList();
    }

    public virtual void Add(T entity)
    {
        _sqlSugarClient.Insertable(entity).ExecuteCommand();
    }

    public virtual void Update(T entity)
    {
        _sqlSugarClient.Updateable(entity).ExecuteCommand();
    }

    public virtual void Delete(int id)
    {
        _sqlSugarClient.Deleteable<T>().In(id).ExecuteCommand();
    }
}

// User数据访问层实现
public class UserRepository : BaseRepository<User>, IUserRepository
{
    public UserRepository(ISqlSugarClient sqlSugarClient) : base(sqlSugarClient)
    {
    }
}

 

业务逻辑层

public class UserService
{
    private readonly IUserRepository _userRepository;

    public UserService(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public User GetUserById(int id)
    {
        return _userRepository.GetById(id);
    }

    public List<User> GetAllUsers()
    {
        return _userRepository.GetAll();
    }

    public void AddUser(User user)
    {
        _userRepository.Add(user);
    }

    public void UpdateUser(User user)
    {
        _userRepository.Update(user);
    }

    public void DeleteUser(int id)
    {
        _userRepository.Delete(id);
    }
}

 

依赖注入配置

public class DependencyInjectionConfig
{
    public static void Configure(IServiceCollection services, string connectionString)
    {
        // 注册ISqlSugarClient实例
        services.AddScoped<ISqlSugarClient>(_ => new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = connectionString,
            DbType = DbType.SqlServer,
            InitKeyType = InitKeyType.Attribute,
            IsAutoCloseConnection = true
        }));

        // 注册数据访问层接口和实现类
        services.AddScoped<IUserRepository, UserRepository>();

        // 注册业务逻辑层
        services.AddScoped<UserService>();
    }
}

 

表现层示例

public class UserController : Controller
{
    private readonly UserService _userService;

    public UserController(UserService userService)
    {
        _userService = userService;
    }

    public IActionResult Index()
    {
        var users = _userService.GetAllUsers();
        return View(users);
    }

    public IActionResult Details(int id)
    {
        var user = _userService.GetUserById(id);
        if (user == null)
        {
            return NotFound();
        }
        return View(user);
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Create(User user)
    {
        if (ModelState.IsValid)
        {
            _userService.AddUser(user);
            return RedirectToAction("Index");
        }
        return View(user);
    }

    public IActionResult Edit(int id)
    {
        var user = _userService.GetUserById(id);
        if (user == null)
        {
            return NotFound();
        }
        return View(user);
    }

    [HttpPost]
    public IActionResult Edit(User user)
    {
        if (ModelState.IsValid)
        {
            _userService.UpdateUser(user);
            return RedirectToAction("Index");
        }
        return View(user);
    }

    public IActionResult Delete(int id)
    {
        var user = _userService.GetUserById(id);
        if (user == null)
        {
            return NotFound();
        }
        return View(user);
    }

    [HttpPost, ActionName("Delete")]
    public IActionResult DeleteConfirmed(int id)
    {
        _userService.DeleteUser(id);
        return RedirectToAction("Index");
    }
}

 

Startup配置

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // 配置依赖注入
        var connectionString = "YourConnectionStringHere";
        DependencyInjectionConfig.Configure(services, connectionString);

        // 注册MVC服务
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

 

这个完整示例展示了如何在C#中构建三层架构,包括数据访问层、业务逻辑层和表现层。数据访问层使用ISqlSugarClient与数据库进行交互,业务逻辑层包含应用程序的核心业务逻辑,表现层负责与用户交互。通过依赖注入,确保每一层之间的松耦合。

posted @ 2024-05-04 08:38  摩诘  阅读(242)  评论(0编辑  收藏  举报