C#: Services access the dataprovider class running the sql statements - correct approach?

白昼怎懂夜的黑 提交于 2019-12-08 11:46:02

问题


is this a common and/or good approach?

In my ViewModel(Wpf) or Presenter(WinForms) I do this:

ICustomerService customerService = MyService.GetService<ICustomerService>();
ICustomerList customerList = customerService.GetCustomers();

the CustomerService class looks like this:

public class CustomerService : ICustomerService
{
     public ICustomerList GetCustomers()
     {
        return _customerDataProvider.GetCustomers();
     }
}

public class CustomerDataProvider()
{
    public ICustomerList GetCustomers()
    {
       // Open SQL connection,
       // get back a SqlDataReader and iterate it
       // in the loop write all data into a ICustomer object
       // add the ICustomer object to the ICustomerList
       // return ICustomerList object... 
    }
}

回答1:


Retrieving data from a database is the plumbing of your application. And the less plumbing you have to write yourself, the more productive you will be.

I usually go to LINQ directly in the client:

 sp_GetCustomersResult customers;
 using (var db = new DbDataContext(ConnectionString))
      customers = db.sp_GetCustomers();

This works fairly well, and lets me focus on adding customer value instead of database access layers.




回答2:


I haven't found much value in declaring interfaces for business classes or for custom collections since extension methods became available. I would have GetCustomers return IEnumerable<Customer>.

If you plan on working extensively with business objects then you should look into using an object/relation mapper such as NHibernate. Or use LINQ2SQL or Entity Framework to reduce the amount of repetitive plumbing code you have to write.



来源:https://stackoverflow.com/questions/3181522/c-services-access-the-dataprovider-class-running-the-sql-statements-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!