top of page

Audit-ability and Traceability design pattern with .Net 6, EF6, Sql server

Updated: Apr 5, 2023

In many industries and applications, it is important to track changes to data and maintain a history of actions taken on that data. This can be useful for auditing, compliance, debugging, and other purposes. In order to achieve this, a design pattern called Audit-ability and Traceability can be used. In this article, we will discuss how to implement this design pattern using .Net 6, EF6, and Sql Server.


Overview of the Audit-ability and Traceability Design Pattern

The Audit-ability and Traceability Design Pattern involves tracking changes to data and maintaining a history of actions taken on that data. This is achieved by creating a set of tables in the database to store the history of changes. The main table stores the current state of the data, while the history table stores the previous states of the data. Each time a change is made to the data, a new record is added to the history table.


Implementation of the Audit-ability and Traceability Design Pattern

To implement the Audit-ability and Traceability Design Pattern using .Net 6, EF6, and Sql Server, follow the steps below:


Step 1: Create a new database or add the necessary tables to an existing database.

This step involves creating two tables in the database: a main table to store the current state of the data, and a history table to store the previous states of the data. Below is an example of the SQL code to create the two tables:

CREATE TABLE MainTable
(
    Id int NOT NULL PRIMARY KEY,
    Name nvarchar(50) NOT NULL,
    Age int NOT NULL,
    Gender nvarchar(10) NOT NULL
)

CREATE TABLE HistoryTable
(
    Id int NOT NULL PRIMARY KEY,
    MainTableId int NOT NULL,
    Name nvarchar(50) NOT NULL,
    Age int NOT NULL,
    Gender nvarchar(10) NOT NULL,
    ChangeDate datetime NOT NULL
)


Step 2: Create a new class in your application that represents the data being tracked.

This step involves creating a class that represents the data being tracked. The class should contain properties for each field in the main table. Below is an example of the C# code for the class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}


Step 3: Use Entity Framework 6 to map the class to the main table in the database.

This step involves using Entity Framework 6 to map the Person class to the MainTable in the database. Below is an example of the C# code for the mapping:

public class MyContext : DbContext
{
    public DbSet<Person> Persons { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .ToTable("MainTable");
    }
}


Step 4: Add a trigger to the main table that will insert a new record into the history table each time a change is made to the data.

This step involves creating a trigger on the MainTable that will insert a new record into the HistoryTable each time a change is made to the data. Below is an example of the SQL code for the trigger:

CREATE TRIGGER MainTable_Audit
ON MainTable
FOR INSERT, UPDATE, DELETEASBEGINDECLARE @Id intSELECT @Id = Id FROM inserted

    IF EXISTS(SELECT * FROM deleted)
    BEGININSERT INTO HistoryTable(Id, MainTableId, Name, Age, Gender, ChangeDate)
        SELECT Id, @Id, Name, Age, Gender, GETDATE() FROM deleted
    END

    IF EXISTS(SELECT * FROM inserted)
    BEGININSERT INTO HistoryTable(Id, MainTableId, Name, Age, Gender, ChangeDate)
        SELECT Id, @Id, Name, Age, Gender, GETDATE() FROM inserted
    ENDEND


Step 5: Create a new class in your application that represents the history table.

This step involves creating a class that represents the HistoryTable in the database. The class should contain properties for each field in the history table, as well as a foreign key property that links it to the MainTable. Below is an example of the C# code for the class:

public class PersonHistory
{
    public int Id { get; set; }
    public int MainTableId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
    public DateTime ChangeDate { get; set; }
}


Step 6: Use Entity Framework 6 to map the PersonHistory class to the history table in the database.

This step involves using Entity Framework 6 to map the PersonHistory class to the HistoryTable in the database. Below is an example of the C# code for the mapping:

public class MyContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<PersonHistory> PersonHistories { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .ToTable("MainTable");

        modelBuilder.Entity<PersonHistory>()
            .ToTable("HistoryTable");
    }
}


Step 7: Implement the auditability and traceability features in your application.

This step involves using the Person and PersonHistory classes in your application to implement the auditability and traceability features. Below is an example of the C# code for retrieving the current state and history of a Person:

using (var context = new MyContext())
{
    // Retrieve the current state of the Person with ID 1var currentPerson = context.Persons.FirstOrDefault(p => p.Id == 1);

    // Retrieve the history of the Person with ID 1var history = context.PersonHistories.Where(p => p.MainTableId == 1);
}

In the above code, the current state of the Person with ID 1 is retrieved using Entity Framework's FirstOrDefault method. The history of the Person with ID 1 is retrieved using Entity Framework's Where method and filtering on the MainTableId property, which is the foreign key that links the PersonHistory to the MainTable.


By using the above implementation steps, you can easily implement auditability and traceability features in your .NET 6 application using Entity Framework 6 and SQL Server.


Benefits of the Audit-ability and Traceability Design Pattern

The Audit-ability and Traceability Design Pattern provides several benefits, including:

  1. Improved data integrity: By tracking changes to the data, the design pattern can help identify and prevent errors and inconsistencies.

  2. Enhanced security: The design pattern can help identify and track unauthorized changes to the data.

  3. Improved compliance: By tracking changes to the data, the design pattern can help ensure compliance with regulatory requirements and industry standards.

  4. Simplified debugging: The design pattern provides a history of actions taken on the data, making it easier to identify and fix issues.


Conclusion

The Audit-ability and Traceability Design Pattern is a powerful tool for tracking changes to data and maintaining a history of actions taken on that data. By implementing this design pattern using .Net 6, EF6, and Sql Server, you can improve data integrity, enhance security, and simplify debugging. By using this design pattern, you can ensure compliance with regulatory requirements and industry standards, making it an essential tool for many industries and applications.

0 comments

コメント


bottom of page