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

Source: Internet
Author: User
Tags assert connectionstrings

Program Architecture

Now compare the classic architecture and look at the picture below.

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 easily realize the database record additions and deletions, but how we go "build it" is more reasonable, more scientific, better use? This is what we really want to learn, using object-oriented interfaces, abstractions to achieve this goal, interface-oriented programming is a better choice to better maintenance and testing.

The following step by step to complete the program, you see the title? This is to break the old idea! Let's see what the mysterious place is next. 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 ORM, we create a LINQ to SQL class DATAACCESSENTITIES.DBML as a data access object DataContext, all visualized operations, in order to demonstrate, in o/ In the R Designer, create a new customer class (data Access Object), add the CustomerID, FirstName, LastName three member properties, and modify the corresponding properties in the Properties window of the member property.

To demonstrate, here is a brief description of my operation, which sets the member properties as follows:

    • CustomerId: The member property of the type int, the name of the property is CustomerId, the name of the database column is CustomerId, the database column participates in the table's primary key true, and the value is automatically generated in the database when inserted true, specifying that the property is automatically synchronized when inserted.
    • 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

Well, the simple data access object is created, and the following test ~ ~

Unit Test Layer

Unit tests are used in the success and failure of test cases, which plays a particularly important role in software development. Of course the requirements of unit testing are very strict, this series I will strictly abide by, I tidy up the requirements as follows

1. Try to provide a description of the error message in the assertion, which makes it easy to find your error.

2. Each test is completely independent and embodies a single principle of responsibility in object-oriented.

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

4. Some of the raw data required for testing is loaded into the database as part of the test before the test method.

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 requires a separate write to delete the SQL statement script.
    • The business logic layer creates data that you don't anticipate, and you're not dealing with it.
    • If you fail the test, viewing the data in the database is not in the database, there is no hint that you do not know what the system has done.
    • Because the record is locked, the inserted data is not written to the database and cannot be read in a different database connection.

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 easy to create a delete database.

Note that this series I use the nunit.framework test, so I want to refer to the Nunit.framework.dll assembly, in addition, because the code is written in this class library reference System.configuration.dll, System.Data.Linq.dll assemblies and Business projects.

1. Create a test base class

Testing is often complicated, we create a test base class to write some common methods, and then all the test classes inherit this test base class, which basically accomplishes the following functions.

First step: Manually configure DataContext connections and logs

In our data access layer, we only created a data access object, did not deal with the database, the test needs to connect to the DataContext database. In addition, to test the display of detailed 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 testing, open a temporary connection for creating the database, using DataContext to provide the databaseexists (), DeleteDatabase (), CreateDatabase () method, first using the databaseexists () Verify that the database exists, and if there is a deletion using the DeleteDatabase () method, create a database schema using the CreateDatabase () method and release the 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

Close all connections at the end of the test, this step is very necessary oh.

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

Fourth step: Setting the connection string

Create a new app. Config file and 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 to test the data Access object, where a simple test creates a customer object, and the new CustomerFixture.cs class inherits Unittestbase

Write the Create Customer object method as follows, 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 testing");    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 testing this method again? This question is left to everyone.

Conclusion

Did you see it? This is the new way to complete a really cool job! It's so easy to start with object-oriented and build its relational database with LINQ to SQL! This article only creates a new data access object on the data access layer and calls the method provided by DataContext to complete the data operation in the test! The next chapter is more exciting!

Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.

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.