This is a mirror of official site: http://jasper-net.blogspot.com/

NHibernate.Envers - a quick introduction

| Tuesday, June 14, 2011
Recently I had the need to introduce a sort of ‘Entity Versioning’ in a portion of my applications, the whole data access strategy was realized using NHibernate + XML / ConfORM mappings.

I started the thing introducing an poor auditing system using a listener and the pre-insert and pre-update events. This will allow me to track who created a record and the last one that modified it (and when) in an easy way (you can find some examples on this technique in a lot of blog posts around, just look for NHibernate + auditing in any web search engine).

The afore mentioned strategy is enough for the great part of my domain, but then I had to move a step forward and not only log who make the action, but also I needed to store the state of the entity at the time it was modified (being it updated or deleted), in short I need the whole history of the changes on that entity. My first thought was to extend my original approach and save the entity in another version of the previous listener...huge work to do!

Then I reminded Fabio Maulo talking about the release of NHibernate.Envers at one of the last UgiAlt workshops I attended to...Gotcha! Let’s take a look at it and see if it fits my needs.

Download the whole source code at https://bitbucket.org/RogerKratz/nhibernate.envers, you need to if you use the latest bits of NHibernate 3.2 because you will need to update the referenced libraries and recompile the project.

Let’s start considering this very simple domain:

public class Person : Entity<int>
{
protected Person()
{
}

public Person(string name, string surname)
{
Games = new List<Game>();
Name = name;
Surname = surname;
}

public string Name { get; set; }

public string Surname { get; set; }

public string Note { get; set; }

public IList<Game> Games { get; set; }

public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Id: {2}, Name: {0}, Surname: {1}, Note: {3}\n", Name, Surname, Id, Note);
sb.AppendLine("Games:");
foreach (var g in Games)
sb.AppendLine(g.ToString());
sb.AppendLine("---");
return sb.ToString();
}

Read more: PrimordialCode

Posted via email from Jasper-net

0 comments: