Link Search Menu Expand Document

Class Handlers


This is a feature that would allow you to handle the event during the serialization/deserialization process of the entity model and the DbDataReader object (inbound/outbound). With this feature, it enables you as developer to handle any kind of serialization event within the model, validation and/or even trigger a workflow during/after the process of transformation.

Imagine the case of validating the model before pushing to the database, or transforming the necessary properties before sending back to the caller.

The execution of the event contains the actual DbDataReader object in used and the affected class model.

Below is the high-level diagram of the class handler.

It uses the following objects

  • IClassHandler - an interface to mark your class as class handler.
  • ClassHandler - an attribute used to map a class handler into a specific .NET CLR type.
  • ClassHandlerMapper - a mapper used to map a class handler into a specific .NET CLR type.
  • FluentMapper - a fluent mapper class used to map a class handler into a specific .NET CLR type.

How does it works?

If you are reading a data from the DB (i.e.: ExecuteQuery, Query, BatchQuery), the method Get() will be invoked after deserializing the model. On the other hand, if you are pushing a data into the DB (i.e.: Insert, Merge, Update), the method Set() will be invoked prior the actual DB operation.

Implementing a Class Handler

Create a class that implements the IClassHandler interface.

public class PersonClassHandler : IClassHandler<Person>
{
    public Person Get(Person entity,
        DbDataReader reader)
    {
        return entity;
    }

    public Person Set(Person entity)
    {
        return entity;
    }
}

Mapping a Class Handler

There are various ways of mapping a class handler into an entity model. You can use either do the following approach.

Firstly, via the ClassHandlerMapper class.

ClassHandlerMapper
    .Add<Person, PersonClassHandler>(true);

Secondly, via the FluentMapper class.

FluentMapper
    .Entity<Person>()
    .ClassHandler<PersonClassHandler>(true);

Lastly, via an explicit ClassHandler attribute.

[ClassHandler(typeof(PersonClassHandler))]
publi class Person
{
    ...
}