使用 Mysql 将我的 WPF 项目转换为 MVVM

本文关键字:转换 MVVM 项目 WPF Mysql 我的 使用 | 更新日期: 2023-09-27 18:32:20

我是C#编码的新手,因此我在开始我的项目时犯了一些错误。这意味着我的所有代码都是在表单中完成的(连接到数据库,执行选择语句和即将进行的更新/插入/删除)。其次,我的大部分代码都是重复的。我有几个表单几乎做同样的事情(唯一的区别是在不同的表上进行选择),如代码所示。

这是来自称为字符的形式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MySql.Data.MySqlClient;
namespace Dark_Heresy
{
    /// <summary>
    /// Interaction logic for Character.xaml
    /// </summary>
    public partial class Character : Window
    {
        public Character()
        {
            InitializeComponent();
        }
        private void character_name_loader(object sender, RoutedEventArgs e)
        {
            string constring = "datasource= localhost; port=3306; username=root; password=Mypass;";
            string Query = "SELECT Name_ FROM dark_heresy.character_";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
            MySqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDatabase.ExecuteReader();
                while (myReader.Read())
                {
                    string charactername = myReader.GetString("Name_");
                    cb_CharacterName.Items.Add(charactername);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: 'r'n" + ex);
            }
        }
        private void cb_CharacterName_DropDownClosed(object sender, EventArgs e)
        {
            string constring = "datasource = localhost; port = 3306; username = root; password = MyPass;";
            string Query = "SELECT * FROM dark_heresy.character_ WHERE Name_='" + cb_CharacterName.Text + "' ;";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
            MySqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDataBase.ExecuteReader();
                while (myReader.Read())
                {
                    string career = myReader.GetString("Class");
                    string world = myReader.GetString("World_Type");
                    string strength = myReader.GetInt32("Str").ToString();
                    string weaponskill = myReader.GetInt32("WS").ToString();
                    string ballisticskill = myReader.GetInt32("BS").ToString();
                    string fellowship = myReader.GetInt32("Fel").ToString();
                    string perception = myReader.GetInt32("Per").ToString();
                    string intelligence = myReader.GetInt32("Int_").ToString();
                    string agility = myReader.GetInt32("Agi").ToString();
                    string willpower = myReader.GetInt32("WP").ToString();
                    string toughness = myReader.GetInt32("Tough").ToString();

                    TextCareer.Text = career;
                    TextWorld.Text = world;
                    TextStrength.Text = strength;
                    TextWeaponskill.Text = weaponskill;
                    TextBallisticskill.Text = ballisticskill;
                    TextFellowship.Text = fellowship;
                    TextPerception.Text = perception;
                    TextIntelligence.Text = intelligence;
                    TextAgility.Text = agility;
                    TextWillpower.Text = willpower;
                    TextToughness.Text = toughness;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: 'r'n" + ex);
            }
        }
        private void cb_Talent_NameDropDownOpen(object sender, EventArgs e)
        {
            string constring = "datasource= localhost; port=3306; username=root; password=MyPass;";
            string Query = "SELECT Talent_Name FROM dark_heresy.learned_talents WHERE Character_Name='" + cb_CharacterName.Text + "' ;";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
            MySqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDatabase.ExecuteReader();
                while (myReader.Read())
                {
                    string talent_name = myReader.GetString("Talent_Name");
                    Talent_Name.Items.Add(talent_name);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: 'r'n" + ex);
            }
        }
        private void cb_Talent_Name_DropDownClosed(object sender, EventArgs e)
        {
            string constring = "datasource = localhost; port = 3306; username = root; password = MyPass;";
            string Query = "SElECT learned_talents.Talent_Name , talents.Description FROM dark_heresy.learned_talents, dark_heresy.talents WHERE learned_talents.Talent_Name = talents.TalentName AND learned_talents.Character_Name = '" + cb_CharacterName.Text + "';";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
            MySqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDataBase.ExecuteReader();
                Talent_Name.Items.Clear();
                while (myReader.Read())
                {
                    string talents_description = myReader.GetString("Description");
                    Talents_Description.Text = talents_description;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: 'r'n" + ex);
            }
        }
        private void Skill_Name_DropDownOpened(object sender, EventArgs e)
        {
            string constring = "datasource= localhost; port=3306; username=root; password=MyPass;";
            string Query = "SELECT Skill_Name FROM dark_heresy.learned_skills WHERE Character_Name='" + cb_CharacterName.Text + "' ;";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
            MySqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDatabase.ExecuteReader();
                while (myReader.Read())
                {
                    string skill_name = myReader.GetString("Skill_Name");
                    Skill_Name.Items.Add(skill_name);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: 'r'n" + ex);
            }
        }
        private void Skill_Name_DropDownClosed(object sender, EventArgs e)
        {
            string constring = "datasource = localhost; port = 3306; username = root; password = MyPass;";
            string Query = "SElECT learned_skills.Skill_Name , skills.Descriptor FROM dark_heresy.learned_skills, dark_heresy.skills WHERE learned_skills.Skill_Name = skills.SkillName AND learned_skills.Character_Name = '" + cb_CharacterName.Text + "';";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
            MySqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDataBase.ExecuteReader();
                Skill_Name.Items.Clear();
                while (myReader.Read())
                {
                    string skills_description = myReader.GetString("Descriptor");
                    Skill_Description.Text = skills_description;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: 'r'n" + ex);
            }
        }

    }
}

一种称为人才的形式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MySql.Data.MySqlClient;
namespace Dark_Heresy
{
    /// <summary>
    /// Interaction logic for Talents.xaml
    /// </summary>
    public partial class Talents : Window
    {
        public Talents()
        {
            InitializeComponent();
        }
        private void cb_loader(object sender, RoutedEventArgs e)
        {
            string constring = "datasource= localhost; port=3306; username=root; password=MyPass;";
            string Query = "SELECT TalentName FROM dark_heresy.talents";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
            MySqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDatabase.ExecuteReader();
                while (myReader.Read())
                {
                    string talentname = myReader.GetString("TalentName");
                    cb_Talents.Items.Add(talentname);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: 'r'n" + ex);
            }
        }
        private void cb_Talent_DropDownClosed_(object sender, EventArgs e)
        {
            string constring = "datasource = localhost; port = 3306; username = root; password = MyPass;";
            string Query = "SELECT * FROM dark_heresy.talents WHERE TalentName='" + cb_Talents.Text + "' ;";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
            MySqlDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDataBase.ExecuteReader();
                while (myReader.Read())
                {
                    string description = myReader.GetString("Description");
                    string strength = myReader.GetInt32("R_Str").ToString();
                    string weaponskill = myReader.GetInt32("R_WS").ToString();
                    string ballisticskill = myReader.GetInt32("R_BS").ToString();
                    string fellowship = myReader.GetInt32("R_Fel").ToString();
                    string perception = myReader.GetInt32("R_Per").ToString();
                    string intelligence = myReader.GetInt32("R_Int").ToString();
                    string agility = myReader.GetInt32("R_Agi").ToString();
                    string willpower = myReader.GetInt32("R_WP").ToString();
                    string toughness = myReader.GetInt32("R_Tough").ToString();

                    TextDescription.Text = description;
                    TextStrength.Text = strength;
                    TextWeaponskill.Text = weaponskill;
                    TextBallisticskill.Text = ballisticskill;
                    TextFellowship.Text = fellowship;
                    TextPerception.Text = perception;
                    TextIntelligence.Text = intelligence;
                    TextAgility.Text = agility;
                    TextWillpower.Text = willpower;
                    TextToughness.Text = toughness;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: 'r'n" + ex);
            }
        }
    }
}

我发现我需要在我的项目中做一些业务逻辑。这让我选择了 MVVM,这意味着我的项目完全做错了。

目前,我唯一的参考是mysql.dll

我已经阅读/看过有关MVVM的教程,但是我有一些问题。

  1. 如果我使用 MVVM 模式,我与 SELECT/UPDATE/INSERT/DELETE 的数据库连接会存储在 ViewModel(业务逻辑)中吗?还是会成为模型的一部分?

  2. 谁能向我解释一下如何更改当前代码,以便它可以从模型到视图模型再到视图?如果可能的话,举个例子。

  3. 模型
  4. ,视图模型应该采用什么形式?WPF、接口、类、类库等。

  5. 有没有人有一些有用的链接可以帮助我解决这个问题,特别是当它与作为定位主机的 MySQL 数据库结合使用时。

使用 Mysql 将我的 WPF 项目转换为 MVVM

我将按顺序解决您的问题:

  1. 不,它们将在模型中。考虑将与数据库相关的所有内容移动到它自己的一层中 - 我建议您查找一种称为存储库的模式及其工作原理(通过接口将存储实现与底层存储技术隔离)。
  2. 您需要做出判断,因为您知道代码在做什么。我建议您阅读有关结构化应用程序的 Prism 库文档,特别是关于模块化应用程序开发的第 4 节 - 这应该会让您对实际应用程序的结构有一个良好的开端。不要担心 Prism 特有的细节,看看视图、视图模型和存储库是如何划分为功能区域的。http://msdn.microsoft.com/en-us/library/gg405479(v=pandp.40).aspx
  3. View 是 WPF XAML,ViewModel 和 Model 通常应该是 C# 类。
  4. 有关 Prism 库文档,请参阅上面的内联文本。

此外,Prism 作为一组类库非常有用,可以作为 MVVM 框架的基础参考,即使您不执行完整的模块引导复合应用程序路由。其中有大量利用 WPF 开发最佳实践的类。对于新手来说,这是一个很好的信息来源,但需要时间来理解这些概念。

更新:"你会将 MVVM 与存储库结合起来吗?

好的,在典型的商业编程中,您将应用程序构建为 3 个不同的逻辑层 - 表示、业务逻辑和数据。存储库通常位于应用程序的数据层中。业务逻辑通常封装一个服务层,其中大多数"真正的"业务逻辑都位于其中(从 MVVM 的角度来看,这将被视为模型的一部分)。演示文稿是 MVVM 所在的位置,特别是 VM 和视图。

每一层将保留/有权访问对下一层中对象的引用,即虚拟机将具有对模型/业务逻辑层的引用

,业务逻辑将具有对数据/存储库层的引用。VM 通常不会直接引用数据层,因为这会破坏分层体系结构并可能导致复杂性。

在某些情况下(混合技术,例如业务逻辑层的TIBCO服务),您甚至不会在应用程序的所有层上工作,而只会在一个层上工作。例如,这就是数据库专家开发人员的用武之地,尤其是在需要专门查询以满足数据仓库系统性能要求的高性能系统中。