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

问题描述 投票:0回答:1

我对C#编程完全陌生,我正尝试自己学习。目前,我正在建立一个迷你项目以进行锻炼。

我了解出于安全原因,用户层不应进行任何数据查询?

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

  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;

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

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

c# winforms data-access-layer
1个回答
0
投票

您已经按照使用Dapper的方式正确地做了所有事情。 Dapper不会维护数据库中实体的局部图,不会跟踪它的更改并自动保存它们。如果需要,请使用类似EF

对于精打细算的人,您可以使用SELECT检索数据,然后使用UPDATE将其发送回去

如果您只希望一个客户作为名称,请执行以下操作:

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

https://dapper-tutorial.net/queryfirst

这将仅返回一个客户实例(或为null;请检查它!),这意味着您可以将表单代码整理为:

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

依此类推

您的“如果最近添加了客户,请尝试更新数据库”实际上没有意义-查询已完成,因此数据库已尽可能保持最新状态。>

© www.soinside.com 2019 - 2024. All rights reserved.