繁体   English   中英

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

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

我对 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;

一切正常,但我不希望用户表单对所有单独的列进行这些查询,因为从我目前所了解的情况来看,这是糟糕的编程,也不利于安全。

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

根据 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

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

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

等等

您的“如果最近添加了客户,请尝试更新数据库”并没有真正意义 - 查询是实时完成的,因此数据库大约是最新的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM