且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何编写一个应该从数据库中获取数据以在C#中的表单上显示的方法

更新时间:2023-09-08 21:00:58

我已经纠正了将db代码与实体分开的解决方案。



我建议让数据库逻辑远离代码的其余部分:



I've corrected my solution for separating db code from entity.

I suggest to keep database logic away from the rest of the code:

public class BankAccount
{
    public string acNo { get; set; }
    public string acName { get; set; }
    public string bank { get; set; }
    public string acType { get; set; }
}

public class BankaccountFactory 
{
    private BankaccountFactory() { } // Default constructor private, so use factory method

    public static BankAccount CreateFromDb(string acNo)
    {
        BankAccount account = new BankAccount { acNo = acNo };

        using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
        {
            SqlCommand newCmd = new SqlCommand("Same SELECT …)", newCon);

            newCmd.Parameters.Add();
            newCon.Open();
            SqlDataReader rdr = newCmd.ExecuteReader();
            rdr.Read();

            account.acName = rdr[1];
            account.bank = rdr[2];
            account.acType = rdr[3];
        }
        return account;
    }
}





然后在表格中使用它:





Then use it like this in your form:

BankAccount acc = BankAccountFactory.CreateFromDB("1021577552254");

txtACName.text=account.acName;
txtBankName.text=account.bank;
txtACType.text=acType;	





根据您的问题:是的,***对您项目中的所有实体执行此操作。如果您在更多项目中使用实体,建议将它们放在单独的类库中以重复使用它们。



According to your question: Yes, it is good practise to do this for all entities in your project. If you are using your entities in more projects it is good advice to place them in a separate class library to reuse them.


对于您的特定情况,第一种方法是可以的,因为它分离了来自表示逻辑的数据访问逻辑。



其他方法都是不好的做法。请记住,引入图层(数据访问,业务和演示)背后的核心原则是每个层都用于执行特定任务。例如,数据访问层仅用于执行数据访问活动,仅此而已。业务层负责编码业务逻辑,而不关心数据获取背后的机制,类似表示层仅用于查看业务层处理的数据。因此,您可以看到明确的责任分离。
For your specific case the first method is okay as it is separating the data access logic from presentation logic.

Rest of the approaches are bad practices. Do remember that the core principle behind introducing layers (Data Access, Business and Presentation) is that each layer is meant to do specific task. For example data access layer is meant to do only data access activities, nothing more. Business Layer is responsible for coding business logic and do not care about the mechanism behind data fetching, similarly Presentation layer is only meant to view the data processed by business layer. So there is clear separation of responsibilities as you can see.