在Winform中使用仓储模式

本文介绍了如何在Winform应用中,利用依赖注入和SqlSugarORM实现一个简单的仓储模式,包括数据库操作(如增删改查)的代码示例和AutoFac的配置。
摘要由CSDN通过智能技术生成

b1aa0f4fc3b812414dc162f4878f153a.png

前言

bb410fe1c2d41e4e24cfbf3daeaa42cf.png

d2ab657c0c9cf5d36cc91f4dc5be20c9.png

    在上一篇中写完了Winform使用依赖注入,这一篇来个小实战,基于依赖注入实现一个简单仓储模式的架构,并使用SqlSugar ORM来访问数据库。

以下代码为了方便,忽略了接口类,若要在实际项目中使用的话,建议分别对RepositoryService加上接口规范约束、降低耦合、方便扩展。

e43ee7a908e3202a94fd202e57bccf3a.png

08f252fa8e2f0d2bcb291cfe8f2ae5bf.gif

540e490a12702aea6fe2f7c350a698cf.jpeg

开发环境:.NET Framework版本:4.8

开发工具:Visual Studio 2022

6198c5a86bd52b103ad19f58c249c239.png

实现步骤

95ab22910a5891240362e72b87b03032.png

  1. 通过Nuget安装System.Data.SQLiteSqlSugar以及AutoFac

  2. 创建数据库实体类,并使用SqlSugar特性标注字段

[Serializable]
    [SugarTable("t_user")]
    public class User
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }


        [SugarColumn(IsOnlyIgnoreInsert = true)]
        public DateTime CreateTime { get; set; }
    }
  1. 创建BaseRepository继承SqlSugar的SimpleClient

public class BaseRepository<T> : SimpleClient<T> where T : class, new()
    {
        public BaseRepository(ISqlSugarClient context = null) : base(context)
        {
        }
    }
  1. 创建UserRepository继承BaseRepository

public class UserRepository:BaseRepository<User>
    {
        public UserRepository(ISqlSugarClient context) : base(context) { }
    }
  1. 创建UserService继承UserRepository

public class UserService:UserRepository
    {
        public UserService(ISqlSugarClient context) :base(context)
        { }
    }
  1. Program中使用AutoFac分别对SqlSugar、Service、Form进行依赖注入

    static void Register()
            {
                var builder = new ContainerBuilder();
    
    
                //SqlSugar注入
                builder.Register(options =>
                {
                    SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
                    {
                        DbType = DbType.Sqlite,
                        InitKeyType = InitKeyType.Attribute,
                        IsAutoCloseConnection = true,
                        ConnectionString = "Data Source=" + Application.StartupPath + "\\data.db"
                    });
                    sqlSugar.Aop.OnLogExecuted = (sql, pars) =>
                    {
                        Console.WriteLine(sql);
                    };
                    return sqlSugar;
                }).As<ISqlSugarClient>();
    
    
                //服务注入
                builder.RegisterType<UserService>();
    
    
                //窗体注入
                var dataAccess = Assembly.GetExecutingAssembly();
                builder.RegisterAssemblyTypes(dataAccess)
                       .Where(t => t.BaseType == typeof(Form) || t.BaseType == typeof(BaseForm));
    
    
                Container = builder.Build();
            }
  1. 在Form中分别实现增删改查

    public partial class Form1 : BaseForm
        {
            readonly UserService _userService;
    
    
            readonly Form2 _form2;
    
    
            BindingList<User> bindList = new BindingList<User>();
            public Form1(UserService userService, Form2 form2)
            {
                InitializeComponent();
                _userService = userService;
                _form2 = form2;
    
    
                dataGridView1.DataSource = bindList;
            }
    
    
            private void btn_query_Click(object sender, EventArgs e)
            {
                var list = _userService.GetList();
                bindList.SetData(list);
            }
    
    
            private void btn_add_Click(object sender, EventArgs e)
            {
                if (_form2.ShowDialog() == DialogResult.OK)
                {
                    User user = new User
                    {
                        Name = _form2.UserName,
                        Age = new Random().Next(1, 100)
                    };
    
    
                    _userService.Insert(user);
                    MessageBox.Show("添加成功");
                    btn_query_Click(null, null);
                }
            }
    
    
            private void btn_edit_Click(object sender, EventArgs e)
            {
                if (dataGridView1.CurrentRow == null)
                {
                    MessageBox.Show("未选中任何行");
                    return;
                }
                int index = dataGridView1.CurrentRow.Index;
                _form2.UserName = dataGridView1[1, index].Value.ToString();
                if (_form2.ShowDialog() == DialogResult.OK)
                {
                    User user = bindList[index];
                    user.Name = _form2.UserName;
                    _userService.Update(user);
                    MessageBox.Show("修改成功");
                    btn_query_Click(null, null);
                }
            }
    
    
            private void btn_remove_Click(object sender, EventArgs e)
            {
                if (dataGridView1.CurrentRow == null)
                {
                    MessageBox.Show("未选中任何行");
                    return;
                }
                int index = dataGridView1.CurrentRow.Index;
                _userService.Delete(bindList[index]);
                MessageBox.Show("删除成功");
                btn_query_Click(null, null);
            }
        }

96c4de81a9c1a9140efd86d21b3b9536.png

实现效果

7cfa1d165699733436265a69b54fb123.png

1c2ed4dad38d4795651e1f52bc74b0ef.gif

☛☛☛点击此处下载源码☚☚☚

24f378425a209b38d4c05a21a89bd4d8.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值