如何将数据查询从用户表单中移开。窗体 C#

How can I move data query away from user form. Winform C#

我是 C# 编程的新手,我正在努力自学。目前我正在构建一个小项目来锻炼。

我明白,出于安全原因,用户层不应该有任何数据查询?

所以我创建了一个单独的数据访问 class 来检索数据。这是我的数据访问 class 的样子(一旦我学会了如何使用它,我将使用存储过程来提高安全性):

  public class DataAccess
{


    public List<Customer> FilteredCustomersList(string name)
    {
        using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal("FineCreteDB")))
        {
            var output = connection.Query<Customer>($"SELECT * from `Customers` WHERE `Cust_Name` LIKE '{name}'").ToList();
            return output;
        }
    }

基本上我从用户表单发送一个字符串来查询数据库,数据被检索并存储在一个列表中。用户表单:

 private void RetrieveData()
    {
        try
        {
            DataAccess db = new DataAccess();
            filteredcustomers = db.FilteredCustomersList(CustomerNameTxtBox_AutoComplete.Text);
            ntn_num = filteredcustomers.Select(x => x.Cust_NTN).ElementAt(0);
            strn_num = filteredcustomers.Select(x => x.Cust_STRN).ElementAt(0);
            address = filteredcustomers.Select(x => x.Cust_Address).ElementAt(0);
            phone_num = filteredcustomers.Select(x => x.Cust_Phone).ElementAt(0);
            id_num = filteredcustomers.Select(x => x.Cust_ID).ElementAt(0);
        }
        catch (Exception)
        {
            MessageBox.Show("Customer not found. If customer was recently added, try updating DB.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            DataAccess db = new DataAccess();
            filteredcustomers = db.AllCustomersList();
            ntn_num = "";
            strn_num = "";
            address = "";
            phone_num = "";
        }
    }

在用户表单端,"filteredcustomers" 保存发回的数据列表,现在这里是问题:我使用 filteredcustomers 列表来提取不同的列像这样的值:

address = filteredcustomers.Select(x => x.Cust_Address).ElementAt(0);

然后使用它们填充相应的文本框,例如:

Address_TxtBox.Text = address;

一切正常,但我不希望用户窗体对所有单独的列进行这些查询,因为据我目前所知,这是糟糕的编程,也不利于安全性。

任何人都可以指导我如何将值保留在数据访问层中并将它们调用到我的表单中吗? 很抱歉,如果这很长 post,我只是在学习,希望尽可能详细。

您已经按照如何使用 Dapper 合理正确地完成了所有操作。 Dapper 不维护来自数据库的本地实体图,跟踪对其的更改并自动保存它们。如果需要,请使用 EF

之类的东西

对于 dapper,您使用 SELECT 检索数据并使用 UPDATE

将其发回

如果您只希望一位客户使用该名称,请执行以下操作:

var output = connection.QueryFirstOrDefault<Customer>($"SELECT * from `Customers` WHERE `Cust_Name` LIKE @n", new { n = name });

https://dapper-tutorial.net/queryfirst

这将 return 只有一个客户实例(或 null;检查它!)意味着您可以将表单代码整理为:

        c = db.FilteredCustomer(CustomerNameTxtBox_AutoComplete.Text);
        ntn_num = c?.Cust_NTN;
        strn_num = c?.Cust_STRN;

以此类推

您的 "if customer was recently added try updating db" 没有任何意义 - 查询是实时完成的,因此数据库几乎是最新的