WPF 结合 MVVM模式下SqlSugar ORM框架的使用

WPF 结合 MVVM模式以及 SQLSugar 是一个强大的应用程序架构,可以用来创建具有良好分层和可维护性的应用程序。以下是一个简单的指导,介绍如何在 WPF MVVM 中使用 SQLSugar 访问 MySQL 数据库。

使用 WPF MVVM 框架结合 MySQL 数据库和 SqlSugar ORM 工具的详细步骤:

1、首先需要安装 SqlSugar 和 MySql.Data 两个 NuGet 包。打开 Visual Studio,右键点击项目 -> NuGet 包管理器 -> 管理解决方案的 NuGet 包,然后搜索 SqlSugar 和 MySql.Data,并安装它们。

2、创建一个名为 Models 的文件夹,在这个文件夹里创建一个名为 DatabaseContext.cs 的类,这个类用于连接到你的 MySQL 数据库。代码如下:

csharp 复制代码
using System;
using SqlSugar;

namespace [your project name].Models
{
    public class DatabaseContext
    {
        private static readonly Lazy<SqlSugarClient> _db = new Lazy<SqlSugarClient>(() =>
        {
            var db = new SqlSugarClient(new ConnectionConfig()
            {
               //参ConnectionString 根据自己项目需求组合
                ConnectionString = "your connection string",
                //ConnectionString = string.Format("server={0};uid={1};pwd={2};database={3}", server, id, pwd, database),
                DbType = DbType.MySql,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });
            // 设置 SqlSugar 日志记录
            db.Aop.OnLogExecuted = (sql, pars) =>
            {
                Console.WriteLine(sql + "\r\n" +
                                  db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            };
            db.Aop.OnError = (exp) => Console.WriteLine(exp.Message);
            return db;
        });

        public static SqlSugarClient Db => _db.Value;
    }
}

其中,ConnectionString 的值应该替换成你的 MySQL 数据库连接字符串。

3、接下来创建一个名为 UserRepository 的类,这个类用于执行用户相关的操作,比如增删改查等。代码如下:

csharp 复制代码
using System.Collections.Generic;
using [your project name].Models;

namespace [your project name].Repositories
{
    public class UserRepository
    {
        public List<User> GetAll()
        {
            return DatabaseContext.Db.Queryable<User>().ToList();
        }

        public void Insert(User user)
        {
            DatabaseContext.Db.Insertable(user).ExecuteCommand();
        }

        public void Update(User user)
        {
            DatabaseContext.Db.Updateable(user).ExecuteCommand();
        }

        public void Delete(User user)
        {
            DatabaseContext.Db.Deleteable(user).ExecuteCommand();
        }
    }
}

其中,User 是你自己定义的实体类,它应该对应着数据库中的一张表。

4、在 ViewModel 中使用 UserRepository 执行数据库操作。可以在 ViewModel 的构造函数中初始化 UserRepository,然后在需要使用时调用它的方法。例如:

csharp 复制代码
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using [your project name].Models;
using [your project name].Repositories;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace [your project name].ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private readonly UserRepository _userRepository = new UserRepository();

        private ObservableCollection<User> _users;

        public ObservableCollection<User> Users
        {
            get => _users;
            set => Set(ref _users, value);
        }

        public ICommand LoadUsersCommand { get; }

        public MainViewModel()
        {
            LoadUsersCommand = new RelayCommand(LoadUsers);

            if (IsInDesignMode)
            {
                // 在设计模式下,添加一些虚拟数据以便在 Visual Studio 中预览界面
                Users = new ObservableCollection<User>()
                {
                    new User() {Id = 1, Name = "张三", Age = 20},
                    new User() {Id = 2, Name = "李四", Age = 25},
                    new User() {Id = 3, Name = "王五", Age = 30},
                };
            }
        }

        private void LoadUsers()
        {
            var users = _userRepository.GetAll();
            Users = new ObservableCollection<User>(users);
        }
    }
}

在 LoadUsers 方法中调用 UserRepository 的 GetAll 方法来获取所有用户,然后把它们转换成 ObservableCollection 给 Users 属性赋值即可。

5、最后,在界面中绑定 ViewModel 的属性和命令。例如:

csharp 复制代码
<Window x:Class="[your project name].MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:viewModels="[your project name].ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <viewModels:MainViewModel />
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding Users}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Id}" />
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                <DataGridTextColumn Header="Age" Binding="{Binding Age}" />
            </DataGrid.Columns>
        </DataGrid>
        <Button Content="Load Users" Command="{Binding LoadUsersCommand}" Margin="10" HorizontalAlignment="Right" VerticalAlignment="Bottom" />
    </Grid>
</Window>

这里使用了 DataGrid 控件来显示用户信息,使用 Button 控件来触发 LoadUsers 命令。注意,必须在 Window 标签中设置 DataContext 属性为 MainViewModel 的实例,这样才能把 ViewModel 中的属性和命令绑定到界面上。

总结

使用 WPF MVVM 模式结合 SQLSugar 访问 MySQL 数据库,可以帮助你创建一个结构良好且易于维护的应用程序。以上步骤为你提供了一个简单的指导,但在实际开发中,你可能需要根据项目的具体需求进行适当的调整和扩展。

相关推荐
Zzz 小生33 分钟前
Claude Code学习笔记(四)-助你快速搭建首个Python项目
大数据·数据库·elasticsearch
nongcunqq4 小时前
abap 操作 excel
java·数据库·excel
rain bye bye5 小时前
calibre LVS 跑不起来 就将setup 的LVS Option connect下的 connect all nets by name 打开。
服务器·数据库·lvs
冻咸鱼5 小时前
MySQL的配置
mysql·配置
阿里云大数据AI技术6 小时前
云栖实录|MaxCompute全新升级:AI时代的原生数据仓库
大数据·数据库·云原生
不剪发的Tony老师6 小时前
Valentina Studio:一款跨平台的数据库管理工具
数据库·sql
weixin_307779137 小时前
在 Microsoft Azure 上部署 ClickHouse 数据仓库:托管服务与自行部署的全面指南
开发语言·数据库·数据仓库·云计算·azure
六元七角八分7 小时前
pom.xml
xml·数据库
虚行7 小时前
Mysql 数据同步中间件 对比
数据库·mysql·中间件
奥尔特星云大使7 小时前
mysql读写分离中间件Atlas安装部署及使用
数据库·mysql·中间件·读写分离·atlas