LINQ to SQL Ingenious (1): It's about breaking old ideas.

Source: Internet
Author: User
Tags assert connectionstrings

Program Architecture

Now compared to the classic architecture, look at the slices.

How to Achieve

How do we use LINQ to SQL in an n-tier application? This is really a problem for the newly-started friends, using LINQ to SQL is ORM technology, can be very easy to implement the database record additions and deletions, but how can we "build it" is more reasonable, more scientific, better use? That's what we really want to learn. Using object-oriented interfaces and abstractions to achieve this goal, interface-oriented programming is a better choice. Able to better maintain and test.

Take the next step to complete the program, you see the title? This article is to break the old idea. See what's going on in the next few magical places.

First create a new project, there are two class libraries are: Data access Layer DataAccess and unit test unittest, see:

Data Access Layer

This article first creates a data access object, because using LINQ to SQL as an ORM, we create a new LINQ to SQL Class DATAACCESSENTITIES.DBML as the data-access object DataContext. All visual operations, in order to demonstrate, create a new customer class (data Access Object) in the O/R Designer. Join CustomerID, FirstName, LastName three member properties. and modify the corresponding property in the properties form of the member property.

To illustrate, here is a brief description of my operation, setting member properties such as the following:

    • CUSTOMERID: The type int of the member property. The name of the property is CustomerID, and the name of the database column is CustomerID. The database column participates in the table's primary key true. In the database at the time of insertion, you are actively generating the value true, specifying that you are actively synchronizing properties when inserting.
    • FirstName: Name of the property FirstName, name of the database column FirstName, other default
    • LastName: Name of the property LastName, name of the database column LastName, other default

OK, simple data access to the object created, the following test ~ ~

Unit Test Layer

Unit test the success and failure of the test example, plays a particularly important role in software development. Of course, the requirements of the unit test are very strict. This series I will strictly abide by, I tidy up the requirements such as the following

1. As far as possible in the assertion to provide error information descriptive narrative, which can be very easy to find your mistake.

2. Each test is completely independent. Embodies the principle of single responsibility in object-oriented.

3. Do not assume that there is any data in the database or what data is not in the database, before each test method to ensure that the database is empty.

4. Some of the raw data needed for testing should be loaded into the database before the test method as part of the test.

Complying with the above requirements, you may face the following problems:

    • To delete each row of data for each table before testing, the PK Association is required to delete the SQL statement script separately.
    • The business logic layer creates data that you do not anticipate, and you do not have merit.

    • Suppose you fail to test, the data in the database is not in the database, no matter what information you do not know what the system did.
    • The inserted data is not written to the database because the record is locked. Nor can it be read in different database connections.

Fortunately LINQ to SQL did everything above, LINQ to SQL DataContext can be used to manage the data schema, which provides databaseexists (), DeleteDatabase (), CreateDatabase () Method makes it very easy to create a delete database.

Attention. I use Nunit.framework to test this series, so I want to refer to the Nunit.framework.dll assembly. Also because this class library references System.configuration.dll, System.Data.Linq.dll assemblies, and business projects in code authoring.

1. Create a test base class

Testing is generally very complex, we create a test base class to write some common methods, and then all test classes inherit the test base class, the base class is mainly completed the following functions.

First step: Manually configure DataContext connections and logs

In our data access layer, we only created a data interview object, did not deal with the database, the test need to connect to the DataContext database.

In addition, in order to test the display of specific information, we also use the DataContext log function.

Public StringConnectionString {Get{if(ConfigurationManager. connectionstrings["Conn"] ==NULL||String. IsNullOrEmpty (ConfigurationManager. connectionstrings["Conn"]. ConnectionString) = =true)         {throw NewInvalidOperationException("The default connection string does not exist or is empty"); }returnConfigurationManager. connectionstrings["Conn"].     ConnectionString; } }PrivateDataaccessentitiesdatacontextM_datacontext; PublicDataaccessentitiesdatacontextDataContext {Get{if(M_datacontext = =NULL) {M_datacontext =NewDataaccessentitiesdatacontext(ConnectionString); M_datacontext.log =Console.         Out; }returnM_datacontext; } }

Step two: Create a database

Before the test. Open a temporary connection for creating the database. Use DataContext to provide the databaseexists (), DeleteDatabase (), CreateDatabase () methods, first using databaseexists () to verify the existence of the database, Assume that there is a deletion using the DeleteDatabase () method. Use the CreateDatabase () method to create a database schema to release this connection in a timely manner.

[Testfixturesetup]Public voidInit () {DataaccessentitiesdatacontextContext =NewDataaccessentitiesdatacontext(ConnectionString); Context. Log =Console. Out;if(Context. Databaseexists () = =true) {context.    DeleteDatabase (); } context.    CreateDatabase (); Context.    Connection.close (); Context.    Dispose (); Context =NULL;}

Step three: Close all connections

This step is necessary to close all connections at the end of the test.

[Testfixtureteardown]  Tear () {    DataContext.Connection.Close ();}

Fourth step: Setting the connection string

Create a new app. config file. To set the connection string:

<?XMLversion="1.0"encoding="Utf-8"?><Configuration> <connectionStrings> <Addname="Conn"connectionString="Data source=.\sqlexpress;initial catalog=linq;integrated security=true"/> </connectionStrings></Configuration>
2. Test class

We create a new test class for testing data access to the object. Here's a simple test to create a customer object. New CustomerFixture.cs class inherits Unittestbase

Write the Create a Customer object method such as the following, create a customer object, call the InsertOnSubmit () method insert, and call the Datacontext.submitchanges () method to submit the database.

[Test]Public voidCreatecustomertest () {CustomerCustomer =NewCustomer() {FirstName ="Yjing", LastName ="Lee"};Assert. AreEqual (0, customer. CustomerId,"CustomerID is 0 before test.");    DataContext.Customer.InsertOnSubmit (Customer); Datacontext.submitchanges ();Assert. Arenotequal (0, customer. CustomerId,"The SubmitChanges () method is called after CustomerID is not 0");}

Test success, look at the output:

Oh! Very cool! The database schema is created first, and then a piece of data is inserted. What will be the result of this method again? This question is left to everyone.

Conclusion

Did you see it? This is the new way to finish the very cool work!

Start with object orientation. Build its relational database with LINQ to SQL. This is all easy!. This article only on the data access layer to create a new data interview object, in the test call DataContext provides method complete data operation!

The next chapter is more exciting!

LINQ to SQL Ingenious (1): It's about breaking old ideas.

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.