Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Access Layer - Designing Class where should responsibility of creating saving be

I am designing Data Access Layer with ADO.NET 2.0 and C#, Sql Server 2005. I often fight with my brain over where to place those calls. Which way of the below i should follow for maintainable robust code.

Method 1

Public Class Company
{

public string CompanyId
{get;set;}

public string CompanyAddress
{get;set;}

public bool Create()
{
}

public bool Update()
{
}

public bool Delete()
{
}

}

Method 2

Public Class Company
{

public string CompanyId
{get;set;}

public string CompanyAddress
{get;set;}
}

and i would use another class like below to do the core data access. Like below

Public Class CompanyRepository
{

public Company CreateCompany(string companyId,string companyDescription)
{
}

public bool UpdateCompany(Company updateCompany)
{
}

public bool DeleteCompany(string companyId)
{
}

public List<Company> FindById(string id)
{
}


}
like image 598
Deeptechtons Avatar asked Jan 15 '12 13:01

Deeptechtons


People also ask

What is the purpose of a data access layer?

A data access layer (DAL) in computer software is a layer of a computer program which provides simplified access to data stored in persistent storage of some kind, such as an entity-relational database. This acronym is prevalently used in Microsoft environments.

Why we use data access layer in MVC?

It lets you work with relational data as objects, eliminating most of the data-access code that you'd usually need to write. Using Entity Framework, you can issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. LINQ provides patterns for querying and updating data.


2 Answers

Go with method 2. It is not the Company class's responsibility to read/write from a data source (single responsibility principle). However, I would even go as far as creating an ICompanyRepository interface and then creating a CompanyRepository implementation for the interface. This way you can inject the ICompanyRepository into the class that needs to save/retrieve company information. It also allows easier unit testing and the ability to create a different implementation in the future (switching from a database to xml files or whatever).

like image 150
Jason Down Avatar answered Nov 14 '22 23:11

Jason Down


If you follow the principle of separation of concerns, you will go with your method 2.

Having different responsibilities in different classes does help with creating testable, maintainable code.

This also produces smaller, more cohesive classes that are easier to write, reason about and check for correctness.

As a note, you can use an ORM instead of hand crafting your data access layer.

like image 28
Oded Avatar answered Nov 14 '22 22:11

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!