LINQ to SQL Ingenious (4): monitor your every move

Source: Internet
Author: User
Tags assert modifier modifiers

Improved

This can also be used in the observer pattern in GOF23, allowing multiple observer objects (object creation, modification) to listen to a Subject object at the same time (this is the data Access object customer). This subject object, when the customer changes state, notifies all observer objects (object creation, modification) so that they can automatically update themselves to monitor the customer's every move.

Let's take a look at this complete architecture first.

Data access Layer 1. Data Access base class

We define a common base class for the entire data Access object, first define the data access base class interface, and let the abstract data access base class implement this interface, which is used to hold the properties common to the data Access object, set to abstract. In our system, not only customer this data access object, in the future will definitely add a lot of, so if in the future to add additional data access objects, simply inherit the base class override property.

STEP1: Defines the data access base class interface:

Public InterfaceIdataaccessbase{intId {Get;Set; }DateTimeCreatedDate {Get;Set; }DateTimeModifiedDate {Get;Set; }stringCreatedBy {Get;Set; }stringModifiedBy {Get;Set; }}

STEP2: Defines an abstract data access base class to implement this interface: For abstract programming, it reduces the coupling to specific classes.

Public abstract classDataaccessbase:Idataaccessbase{public Abstract intId {Get;Set; }Public AbstractDateTimeCreatedDate {Get;Set; }Public AbstractDateTimeModifiedDate {Get;Set; }Public Abstract StringCreatedBy {Get;Set; }Public Abstract StringModifiedBy {Get;Set; }}
2. Data Access Object Customer

Since the abstract IDs, CreatedBy, CreatedDate, ModifiedBy, ModifiedDate, and so on are defined in the data access base class, we modify the properties of the data Access object customer, and see

Modify the Customer class, add the CreatedBy, CreatedDate, ModifiedBy, modifieddate attributes, and change the CustomerID to the ID, specifically, the modifiers of these field properties must be modified to override the " Override ".

Modifies the data access object of the customer interface, inheriting the data access base class interface Idataaccessbase.

public interface  icustomer : idataaccessbase  {int  Id {get ; set ; } string  FirstName {get ; set ; } string  LastName {get ; set ; }}

Modify the data Access object customer partial class, inherit the data Access base classes interface Idataaccessbase and the data Access object customer interface, then the data Access object customer total seven properties.

Dataaccessbase Icustomer {}

Data Access object Customer modification completed, if we want to add additional data access objects, it is easy to expand, it is easy to rewrite their own properties.

3. Data Access Object DataContext

Defines the data Access object DataContext partial class Dataaccessentitiesdatacontext, which is used to hold public methods for manipulating objects, such as who created the data? When was this data created? Who modified the data? When was it modified? We can rewrite the built-in method implementations of LINQ to SQL.

DataContext defines the following three partial methods for each entity: Insertentityname (), Updateentityname (), Deleteentityname ().

We have added the customer class in the or designer, with a built-in definition of three partial methods:

InsertCustomer (instance);  UpdateCustomer (instance);  DeleteCustomer (instance);

We will rewrite the above three methods to realize the effect of observation, when overriding the above method needs to call the Executedynamicinsert (), Executedynamicupdate (), Executedynamicdelete () method.

    • Executedynamicinsert () method: called in the Insert Override method to re-delegate the task of generating and executing the dynamic SQL of the insert operation to the LINQ to SQL.
    • Executedynamicupdate () method: Called in the update override method to re-delegate the task of generating and performing update operations to LINQ to SQL for dynamic SQL.
    • Executedynamicdelete () method: called in the Delete override method to re-delegate the task of generating and performing a delete operation to a LINQ to SQL Dynamic SQL.

We rewrite the new partial class DataAccessEntitiesDataContext.cs, which overrides the specific implementation of the above three partial methods in this partial class. In this article I only need to rewrite the InsertCustomer method (triggered when inserting a customer) and UpdateCustomer (triggered when updating the customer) two methods, in order for the program to be reused, we insert the data to access the object, When you modify a data access object, the record information is encapsulated into two method implementations.

STEP1: Create a data Access Object implementation record creator (get machine Current user name) and creation time, because the modified field is not empty, the information is used by default when it is created.

private voidInsertdataaccessbase (DataaccessbaseInstance) {//When creating objects (record creator and time)Instance. CreatedBy =WindowsIdentity. GetCurrent ().    Name; Instance. CreatedDate =DateTime. Now;//Modify object (record modifier and time)Instance. ModifiedBy =WindowsIdentity. GetCurrent ().    Name; Instance. ModifiedDate =DateTime. Now;//In Insert override method call//re-delegate the task of generating and executing the dynamic SQL of the insert operation to the LINQ to SQLExecutedynamicinsert (instance);}

STEP2: Modify data Access object implementation record modifier (get machine Current user name here) and modify time.

Updatedataaccessbase (instance) {    //Modify object (record modifier and time)    WindowsIdentity. GetCurrent (). Name;    DateTime. Now;    Executedynamicupdate (instance);}

STEP3: Override the InsertCustomer () partial method, and call the Insertdataaccessbase () method.

InsertCustomer (instance) {    insertdataaccessbase (instance);}

STEP4: Override the UpdateCustomer () partial method, and call the Updatedataaccessbase () method.

UpdateCustomer (instance) {    updatedataaccessbase (instance);}

If the system has to add other data access objects, if you want to implement the logging function only need to call the Insertdataaccessbase (), Updatedataaccessbase () method, which improves the reusability of the code.

4. Data Access object Customer appearance facade

This same as, without any changes, the appearance of facade dependencies for the customer interface, where the customer interface has not changed Oh!

Unit Test Layer

All of the above work is inseparable from testing! Only through testing, we can verify the correctness of our program! Well, let's start, since we've modified the data Access object, we have to modify the corresponding test!

1. Create a data Access Object test

Test to create a data access object to compare the creator with the machine user name!

[Test]Public voidUpdatetest () {IcustomerNewcustomer = Createandsavenewcustomer ("Yjing","Lee");Assert. Arenotequal (0, newcustomer.id);Assert. AreEqual ("Yjing", newcustomer.firstname);Assert. Arenotequal (DateTime. MinValue, newcustomer.createddate);Assert. Arenotequal (DateTime. MinValue, newcustomer.modifieddate);Assert. Isnotnull (Newcustomer.createdby);Assert. Isnotnull (Newcustomer.modifiedby);//Get machine Current user name    stringCurrentUserName =WindowsIdentity. GetCurrent (). Name;//Compare creators and modifiers    Assert. AreEqual (CurrentUserName, Newcustomer.createdby);Assert. AreEqual (CurrentUserName, newcustomer.modifiedby);}

The test output is as follows

Analysis: First verify that the database exists, there is a delete, and then recreate a new database schema and Customer table, this table has 7 fields. We inserted a data into the database and the system automatically added information such as creator, creation time, modifier, modification time, and so on.

2. Modifying data Access Object testing

Now that we have added this feature, let's test the validation by inserting a piece of data and then waiting for 3 seconds to update the object to see if the modification time is our expected change value.

[Test]Public voidModifycustomerupdatesmodifieddatetest () {IcustomerTempcustomer = Createandsavenewcustomer ("Yjing","Lee");DateTimeOriginallastmodifieddate = tempcustomer.modifieddate;Thread.    Sleep (1500); Tempcustomer.firstname ="Cnblogs"; Facade.updatecustomer (Tempcustomer);Assert. Arenotequal (Originallastmodifieddate, tempcustomer.modifieddate);}

The test output is as follows:

This omits the process of creating a database, inserting an object in the first sentence, updating an object in the second sentence, and looking closely at whether its modification time has changed.

Let's test some of the original tests!

Conclusion

This article uses the method of rewriting the partial method, realizes the very cool function, monitors the data at all times. Also from the design point of view to the abstract programming, reduce the coupling with the specific class. We seldom deal with the customer class here.

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

LINQ to SQL Ingenious (4): monitor your every move

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.