How to build your own data access Layer 3

Source: Internet
Author: User

In the previous article, how to build our own data access layer 2, we have implemented the corresponding features of the data access layer. Now we have finished the work. Let's take a look at the code section and try the features of the previous article:

 
 
  1. String sqlText = "select id, NAME, val from test ";
  2. String columns = "ID, NAME, VAL ";
  3. DataSet ds = new DataSet ();
  4. DataExecutor execObj = new MSSqlExecutor ();
  5. DataMapping map = new DataMapping ();
  6. Map. ExecuteObject = execObj;
  7. Map. TableName = "TEST ";
  8. Map. KeyColumns = "ID ";
  9. Map. Columns = "ID, NAME, VAL ";
  10. DataMapping map = new DataMapping (execObj. GetInstant (), "TEST", "ID", columns );
  11. Map. Fill (sqlText, "TEST ");
  12. Map. SetCommands (DataCommandType. Insert | DataCommandType. Update | DataCommandType. Delete, ds );
  13. // Add, delete, and modify data in DataTable Mode
  14. Bool isSuccess = execObj. Update ();

I have completed the read and write operations on the database. At least I don't need to write a large segment of parameter passing code. All the functions have been implemented. Is that all done?

Take a closer look at the above Code. In fact, there are still problems that have not been solved. Let's look at this sentence:

 
 
  1. DataExecutor execObj = new MSSqlExecutor(); 

The execution object of MSSql is instantiated directly in the Code, so that the switching problem between databases proposed at the beginning is not fundamentally solved.

Let's look at the previous article. There is a method of public IDbConnection GetConn (), which is used to obtain the data connection object. It didn't explain how to implement it before.

We know that DBConnection has two key information:

1. What kind of database is connected to? This is already solved.

2. Pass the account information connected to the database and the ConnectionString of the database access information, which is not mentioned.

Let's see how it was previously done at the second point:

 
 
  1. Public IDbConnection GetConn ()
  2. {
  3. If (conn! = Null)
  4. {
  5. Return conn;
  6. }
  7. Conn = new SqlConnection ();
  8. Conn. ConnectionString = connection string;
  9. Return conn;
  10. }

Where does the connection string come from?

In summary, to complete the final data access output, two problems need to be solved:

1. dynamically switch between different databases.

2. Solve the Problem of data connection string source.

Next we will solve these two problems. First we will solve the second problem. There is a simple method to write the connection string into the configuration file, the data access layer only needs to know the KEY value it passes:

 
 
  1. <appSettings>  
  2.     <add key="ConnStr" value="server=.;uid=sa;password=123456;database=DATA_BASE;max pool size=300"/>  
  3. </appSettings> 

The first problem is solved, and only the last one is left. How can we dynamically switch different databases? That is to say, we don't need to create a NEW object when using it, instead, we create an object through a third party. In fact, we have proposed a solution in the design mode. If you are interested, you can study it on your own. Here we only need to use the simple factory mode:

 
 
  1. public sealed class ExecutorFactory  
  2. {  
  3.     public static DataExecutor Create()  
  4.     {  
  5.         return Create(DatabaseType.MSSql);  
  6.     }  
  7.     public static DataExecutor Create(DatabaseType dbType)  
  8.     {  
  9.         AbstractDataBase dataBase = null;  
  10.         Switch(dbType)  
  11.         {  
  12.             case DatabaseType.MSSql:  
  13.                 dataBase = new MSSqlDataBase();  
  14.                 break;  
  15.             case DatabaseType.Oracle:  
  16.                 dataBase = new OracleDataBase();  
  17.                 break;  
  18.         }  
  19.         return dataBase.Create();  
  20.     }  

Now you can replace this code: DataExecutor execObj = new MSSqlExecutor ();

Replace with: DataExecutor execObj = ExecutorFactory. Create ();

At this point, the problem has been solved. to switch to a database, you only need to change DatabaseType to the corresponding database type.

Next, let's take another consideration. If the database type does not need to be changed, can it be implemented?

The configuration file is used, but not the type string provided at this time, but the actual information of the Data executor assembly, which can be achieved by using. NET's natural advantage reflection.
The final configuration file is:

 
 
  1. <appSettings>  
  2.     <add key="ConnStr" value="server=.;uid=sa;password=123456;database=DATA_BASE;max pool size=300"/>  
  3.     <add key="DBExecutor" value="FM.DataAccess, FM.DataAccess.MappingExcuter.MSSqlExecutor"></add>  
  4.   </appSettings> 

Transformed Factory:

 
 
  1. public sealed class ExecutorFactory  
  2.     {  
  3.         public static DataExecutor Create()  
  4.         {  
  5.             return Create(null);  
  6.         }  
  7.         public static DataExecutor Create(string dataBaseTypeKey)  
  8.         {  
  9.             return Create(dataBaseTypeKey, null);  
  10.         }  
  11.         public static DataExecutor Create(string dataBaseTypeKey, string connStrKey)  
  12.         {  
  13.             if (string.IsNullOrEmpty(dataBaseTypeKey))  
  14.             {  
  15.                 dataBaseTypeKey = "DBExecutor";  
  16.             }  
  17.             string[] sltDataBaseType = ConfigReader.Read(dataBaseTypeKey).Split(',');  
  18.             string asselblyName = sltDataBaseType[0];  
  19.             string nameSpace = sltDataBaseType[1].Trim();  
  20.             Assembly assembly = Assembly.Load(asselblyName);  
  21.             DataExecutor execObj = assembly.CreateInstance(nameSpace) as DataExecutor;  
  22.             execObj.SetConnectionString(connStrKey);  
  23.             return execObj;  
  24.         }  
  25.     } 

So far, the data access layer has finally been completed. Of course, there are still many problems to solve here, but its basic framework has been formed. Based on this, we can achieve our own expansion based on business changes, only by constantly updating can we form a complete data access layer.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.