Many developers have confusion about how to write database code in an application. I will discuss several approaches here and try to provide the explanation for each approach.
Approach 1
This is the easiest and very straightforward approach that will work absolutely fine. I am assuming you already have an understanding of design principles. I am just exploring the different approaches to achieve the database connectivity.
- using System.Collections.Generic;
- using System.Data.SqlClient;
- namespace DatabaseFactory {
- class Program {
- static void Main(string[] args) {
- var employees = SomeDabOperation();
- }
- private static List < Employee > SomeDabOperation() {
- using(SqlConnection myConnection = new SqlConnection("connectionString")) {
- using(SqlCommand myCommand = new SqlCommand("Select * From Employee", myConnection)) {
- using(SqlDataReader reader = myCommand.ExecuteReader()) {
- //Some Code.......
- }
- }
- }
- return new List < Employee > ();
- }
- }
- public class Employee {}
Approach 2
How about the below code? Just a single line! Isn't it more clean than the earlier approach?
Where did the rest of the code get moved? Of course, we can't remove the code and we have just moved it to a separate class.
- namespace DatabaseFactory {
- class Program {
- static void Main(string[] args) {
- var employees = DatabaseManager.SomeDabOperation();
- }
- }
- }
We can see the benefit of moving database logic to different layer - we are not bothered if the database will get changed in the future, it's much more readable than before etc.
- using System.Collections.Generic;
- using System.Data.SqlClient;
- namespace DatabaseFactory {
- internal class DatabaseManager {
- internal static object SomeDabOperation() {
- using(SqlConnection myConnection = new SqlConnection("connectionString")) {
- using(SqlCommand myCommand = new SqlCommand("Select * From Employee", myConnection)) {
- using(SqlDataReader reader = myCommand.ExecuteReader()) {
- //Some Code.......
- }
- }
- }
- return new List < Employee > ();
- }
- }
- public class Employee {}
- }
Approach 3
Before writing the cleaner method of Database Factory, let's explore the use of web.cofig/app.config in the implementation.
App.config
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <configSections>
- <section name="DbFactoryConfiguration" type="GuruBook.Store.DbFactorySectionHandler, GuruBook.Store" /> </configSections>
- <connectionStrings>
- <clear/>
- <add name="sqlConnectionString" providerName="System.Data.SqlClient" connectionString="DataSource=W10FMV4P72\SQLEXPRESS;Initial Catalog=FitBook;Integrated Security=True;" /> </connectionStrings>
- <DbFactoryConfiguration Name="GuruBook.Store.DataStores.SqlDataBase" ConnectionStringName="sqlConnectionString" />
- </configuration>
Create a class to read custom section

Guest UserPosted Aug 27, 2019, 6:03 AM
Nice article, do you have any example for repository pattern that uses the database factory.