LA.NET [EN]

NHibernateArchive

May 12

After hearing lots of good things about EF 4.1 and its new code first approach, I’ve decided to take a look to see if it’s as good as they say. I must admit: the latest version has lots of good things, but it still is far far away from my favorite ORM (which, btw, is NHibernate). To test the code first approach, I’ve tried to build a simple model which reproduces most of the features I tend to use in day-to-day database persistence operations. This isn’t a real case example, but it’s close enough for seeing if it does what I want:

public class Address:ValueObject {
    private Address() {
        Street = Municipality = "";
    }
    public Address( string rua, string localidade ) {
        Street = rua;
        Municipality = localidade;
    }

    public String Street { get; private set; }
    public String Municipality { get; private set; }
}

public enum EntityKind {
    Individual,
    Coletiva
}
    public enum ContactKind {
    Phone,
    Email
}

public class Contact:ValueObject {
    public String Valor { get; private set; }
    public ContactKind ContactKind { get; private set; }

    public Contact( string valor, ContactKind contactKind ) {
        Valor = valor;
        ContactKind = contactKind;
    }

    private Contact() {
        Valor = "";
        ContactKind = ContactKind.Phone;
    }
}
public abstract class Entity:EntityWithAction {
    public String Name { get; set; }
    public Address Address { get; set; }
    public DomainAction Action { get; set; }
    public abstract EntityKind EntityKind { get; }

    private IList<Contact> _contacts = new List<Contact>();
    public IEnumerable<Contact> Contactos {
        get{ return new ReadOnlyCollection<Contact>( _contacts );}
        set { _contacts = new List<Contact>(value); }
    }
    public void AddContact(Contact contact) {
        _contacts.Add( contact );
    }
    public void RemoveContact(Contact contact) {
        _contacts.Remove( contact );
    }
}

public class Individual:Entity {
    public override EntityKind EntityKind {
        get { return EntityKind.Individual; }
    }
}
public class Company:Entity {
    public override EntityKind EntityKind {
        get { return EntityKind.Coletiva; }
    }
}

So, what do we have here:

  • we’ve got inheritance: just for the kicks, I want to have two different kinds of entity and they should be saved in the same table.
  • we’ve got components (I believe they’re called complex types in EF). Notice that Address is a component and Entity has a collection of components (Contacts).
  • I don’t want to allow direct access to  thecontact collection to anyone consuming my domain. All additions and removals should go through the Add/Remove methods.
  • I want to preserve my domain object’s behavior. I’ve got entities (ex.: Individual) and value objects (ex.: Address) with quite distinct behaviors. Notice also those ValueObject and EntityWithAction base classes… They’re inspired in the fantastic S#arch classes (whose use I recommend) and solve several interesting problems (like equality and hash computation) for entities and value objects.

After a morning trying to make my mappings work, I’ve simply quit. Here are some things which really bother me:

  • EF doesn’t seem to support collection of components. With NH, I can simply say that updating an entity should always delete and insert its contacts on a related table. Is this doable in EF? Because this kind of behavior shouldn’t require any back pointer in my Contact object…
  • EF requires the use of ICollection interface for associated entities. This isn’t really compatible with a real domain model where I do need to control what is done over an instance of an object.
  • There still isn’t enum support.
  • The fluent API for registering isn’t really that fluent. Worst: it has overloads of methods which return different types (yes, the CLR does support those overloads, but the C# will only allow it for different parameter lists). This leads to frustration really quickly. For instance, I’ve spent several minutes trying to define the discriminator column only to find out that the Require overloads return different results…which don’t “flow”…really…
  • I really didn’t get far enough to see if I could define the mapping at the field level, but I’m assuming that isn’t possible.

Probably these problems can be easily solved…probably not. I don’t know because I just gave up! Why did I gave up? Well, simply because there’s NHibernate which can do all this for me in a rather quick way, without any pain, and with very little changes in my domain model. And that’s why I’ll keep using NH for my domain and I’ll probably resort to EF for the reporting side of my apps…I’m sorry, but I think that EF is still nor ready for real domain models…

Apr 26

One of the nice things you can do to improve the code we’ve seen in the previous post is define the validation rules in an external assembly. By doing this, you can change your rules without having to recompile the assembly that contains the domain objects. To illustrate this, we’ll change the example presented in the last post.

The first thing we’ll do is create a new class library assembly to host our Student class. I’m calling it OO and changing the default namespace of the Student class:

namespace OO {
    public class Student     {
        public Student(Int32 studentId) {
            StudentId = studentId;
        } 
        public Int32 StudentId { get; private set; }
        public String Name { get; set; }
        public String Email { get; set; }
    }
}

Then, we need another (class library) assembly which references NHibernate.Validator and our OO assemblies. This is where we’ll put our validation rules. In this case, I’ve called the assembly OO.Rules and I’ve decided to go with the fluent interface approach. Here is the code of the StudentRules class (which has all the validation rules for the Student class):

namespace OO.Rules {
    public class StudentRules: ValidationDef<Student>    {
        public StudentRules()        {
            Define(st => st.StudentId).GreaterThanOrEqualTo(1)
                                                     .WithMessage("StudenId must be positive");
            Define(st => st.Name).NotEmpty()
                                              .WithMessage("Name cannot be empty")
                                              .And.NotNullable()
                                              .WithMessage("Name cannot be null");
            Define(st => st.Email).IsEmail().WithMessage("Email is not correct");

        }
    }
}

Finally, I’m building a console app for testing the code. After adding all the necessary references (don’t forget to reference our 2 custom assemblies and the NH validator assembly), you’ll only need this code for getting the same results we had with the previous posts:

var fluentConfig = new FluentConfiguration();
((IMappingLoader)fluentConfig).AddAssembly("OO.Rules");
fluentConfig.SetDefaultValidatorMode(ValidatorMode.UseExternal);
var validator = new ValidatorEngine();
validator.Configure(fluentConfig);

var student = new Student(-1) {
                Name = "Luis",
                Email = "labreu"
};

var invalidValues = validator.Validate(student);
//same code as before

As you can see, the main difference (when compared with the previous example) happens in the setup of the FluentConfiguration instance. Instead of registering each validated type, we’re simply passing the name of the assembly and letting the framework pick all the types and their validation rules.

In my opinion, this approach (of separating rules from validated objects) has two advantages:

  • you can easily change the rules without needing to recompile the assembly that contains your objects;
  • the OO assembly no longer needs to reference the NH validator assembly.

And that’s it for today.

Apr 24

After started looking at the S#arp framework, I was almost obliged to take a look at NHibernate Validator framework .To see if it was really that good, I decide to pick a small example and apply some validation rules. This post contains some notes on my incursion into this framework.

The first thing you need to do is to download the library and add a reference to in your project. Then, you can start adding validation rules to the properties of your objects. Currently, you have three options: you can use attributes and decorate your fields/properties with the available attributes, or you can use an XML file to define those rules or you can define those rules by using a fluent interface approach. We’ll start by exemplifying attribute usage. Take a look at the following snippet:

namespace TestApp {
    public class Student    {
        public Student( Int32 studentId ) {
            StudentId = studentId;
        }

        [Min(1, Message="StudenId must be positive")]
        public int StudentId { get; private set; }
        [NotEmpty (Message="Name cannot be empty"), NotNull(Message="Name cannot be null")]
        public String Name { get; set; }
        [Email(Message="Email is not correct")]
        public String Email { get; set; }
    }
}

As you can see, we’re using several of the validation attributes and we’re also specifying an error message for all of them. You are now in a position to validate an instance of Student by using the ValidatorEngine class:

var invalidId = -1;
var student = new Student( invalidId ) {
           Name = "Luis",
           Email = "labreu@"
};

var validator = new ValidatorEngine( );
var invalidValues = validator.Validate( student );
foreach ( var invalidValue in invalidValues ) {
    Console.WriteLine( "Property: {0} —- PropertyPath:{1} —– Message: {2}n",
                    invalidValue.PropertyName,
                    invalidValue.PropertyPath,
                    invalidValue.Message );
}

If you run the previous snippet,you should get errors for the Student’s Id and email properties!

As I said, you can also specify the validation rules by using XML files. Here are the validation rules written on a xml file:

<?xml version="1.0" encoding="utf-8" ?>
<nhv-mapping xmlns="urn:nhibernate-validator-1.0" namespace="TestApp" assembly="TestApp">
  <class name="Student">
    <property name="StudentId">
      <min value="0" message="StudenId must be positive" />
    </property>
    <property name="Name">
      <not-empty message="Name cannot be empty" />
      <not-null message="Name cannot be null" /> 
    </property>
    <property name="Email">
      <email message="Email is not correct" />
    </property>
  </class>
</nhv-mapping>

Now, you have two options: you can embed the XML file or just copy it to same place on the disk (generally, you’ll put them on the same folder as the app). In both cases, you’ll need to pass a config options to the ValidatorEngine object. Here’s the code you might use when you’re using an external config file (do notice that if the config file is embedded, you’ll still need to set the ValidatorMode property):

using Environment = NHibernate.Validator.Cfg;

//more code

var configOptions = new NHVConfigurationBase( );
configOptions.Mappings.Add( new MappingConfiguration( "Student.nhv.xml" ) );
configOptions.Properties[Environment.Environment.ValidatorMode] = ValidatorMode.UseExternal.ToString( );
var validator = new ValidatorEngine( );
validator.Configure( configOptions );
var invalidValues = validator.Validate( student );
//same code as before for showing error msgs

You should also keep one more thing in mind (if you decide to go with the embedded resource approach): if you want to get automatic loadding, then you should give the file the same name that you gave to the class.

Before ending, there’s still time for showing one last option for setting up the rules: using a fluent configuration style. If you prefer this approach, the first thing you need to do is create a class for the  definition. Here’s how it looks:

public class StudentRules : ValidationDef<Student> {
   public StudentRules( ) {
                Define( st => st.StudentId ).GreaterThanOrEqualTo( 1 ).WithMessage( "StudenId must be positive" );
                Define( st => st.Name ).NotEmpty( ).WithMessage( "Name cannot be empty" )
                    .And.NotNullable( ).WithMessage( "Name cannot be null" );
                Define( st => st.Email ).IsEmail( ).WithMessage( "Email is not correct" );
    }
}

And then, you can load your rules like this:

FluentConfiguration fluentConfig = new FluentConfiguration( );                                 
fluentConfig.Register<StudentRules, Student>( )
                                    .SetDefaultValidatorMode( ValidatorMode.UseExternal );

var validator = new ValidatorEngine( );
validator.Configure( fluentConfig );
//the rest remains the same

I won’t say anything more about this framework today. The only thing I’ll add is that I did enjoy it and I‘ll come back to it in the future (especially because it does integrate really well with NH and I’ll be talking about that and S#arp framework in a near future).

Oct 24

Using the new Fluent NHibernate project

Posted in C#, NHibernate       Comments Off on Using the new Fluent NHibernate project

If you’re a NHibernate user, you’ve surelly heard about the Fluent NHibernate, a project that allows you to define the mappings by using a fluent API. I didn’t really had the time for testing it until yesterday. Why did I only tested it yesterday? Simple: because I had to perform some major refactorings on the current project I’m working and that meant having to go through the XML mappings files and changing all those damn properties by hand. Yes, it was the perfect excuse for introducing the fluent mapping in my project.

Overall, I’m pleased with it, but since there really aren’t many docs on how to use them, I thought it would be a good idea to give some examples of its use here and to point one or two gotchas that you might get while using it. Before using it, do keep in mind that there are some options which aren’t implemented yet (but I think it’s fair to expect them to be implemented in a near future). Having said this, it’s time to show some examples. Lets start by building a dumb class and call it Entity:

class Entity{
  public Int32 Id{ get; private set; }
  public Int32 Version{ get; set; }
  public String Name{ get; set; } 
}

We’ve got an ID, a version and a property. Lets map them to columns of a table called Customers, without lazy loading:

class EntityMapping: ClassMap<Entity>{
  public EntityMapping(){
     WithTable( “Customers” ); //set table name
     SetAttribute( “lazy”, “false”); //no lazy loading
     Id( ent => ent.Id,“IdCustomer” ) //Id prop into column IdCostumer
       .WithUnsavedValue(0)
       .SetGeneratorClass(“identity”);
     Version( ent => ent.Version).TheColumnNameIs(“MyVersion”);
     Map( ent => ent.Name,“CustomerName”)
       .WithLenghtOf(200)
       .CanNotBeNull();
  }
}

This basic mapping introduces several important concepts. All the configuration classes should inherit from ClassMap<T>. Setting the table name is easy: just call the WithTable method and that’s it. You can also use the SetAttribute method for setting up the other attributes you would normally set on you <class> element. In the previous example, I’ve just used it to change the default lazy loading behaviour.

Setting the Id and Version properties are easy too: just call the Id and Version methods. Do notice that you didn’t really need to write all that code if you’re using the defaults (I never know which is which and that is why I generally end up writing everything I remember :))

Simple properties are mapped through the Map method. Notice that in the previous example we indicate all the column names because they’re different from the properties names we’ve been using.

First rant: I really don’t like calling these methods from the constructor because we’re talking about virtual methods. Unfortunately, the current version doesn’t have any other hook I can use for setting up the mappings.

Second rant: SetAttribute retuns void, which means that if you want to call it several times, you can’t use a fluent approach.

Ok, let’s move on. Now I want to add a collection of entities to my entity. In this case, Entity can have several Branches and  Branch belongs only to one entity. Here’s the necessary changes to the Entity class:

class Entity{
  //previous code
  private ISet<Branch> _branches;
  public ISet<Branch> Branches  {
     get { return new ImmutableSet<Branch>(_branches); }
     private set{ _branches = value;}
  } 
}

For now, you just need to keep in mind that Branch is an entity with some properties and that it has its own configuration file. You can easilly map this relationship by using code similar to this:

class Mapping: ClassMapping<Entity>{
    public Mapping() {
     //previous code
     HasMany<Branch>(ent => ent.Branches)
                .AsSet()
                .Cascade
                .All()
                .WithKeyColumn("IdEntidade");
  }
}

As you can see, you specify a set by calling the AsSet method and then, if you want, you can also set the cascade and key column name. You’ll also find other AsXXX methods that you can use for the other types of collections (ex.: bags).

Another thing which you’ll need to represent is many-to-one relationships. For instance, suppose we’ve updated the Entity class so that it looks like this:

class Entity{
  //previous code
  public DomainAction Action{ get; internal set; }
}

DomainAction is another entity which has its own table. The References method can be used here for mapping the many-to-one relationship between Entity and DomainAction:

class EntityMapping: ClassMap<Entity>{
  public Mapping() {
     //previous code
     References( ent => ent.Action, "ActionId")
               .Cascade
               .SaveUpdate();
  }
}

When you get the mappings, you’ll see that the Customer table will have a column called ActionId, which holds the ID of the associated Action. Ok, pretty similar to the previous configuration code, right? Oh. lets add a component to our entity. We’ll call it Address:

class Entity{
  //previous code
  public Address Address{ get; set; }
}

Address is a class that implements what I like to call the value object pattern. Just by looking at the mapping code, you should be able to see what’s going on:

class EntityMapping:ClassMap<Entity>{
  public EntityMapping(){
    //previous code
      Component<Address>(branch => branch.Address,
                              address =>
                                  {
                                      address.Map(a => a.Street, "St")
                                          .WithLengthOf(300);
                                      address.Map(a => a.ZipCode, "ZC")
                                          .WithLengthOf(100);
                                      address.References(a => a.CivilParish)
                                          .TheColumnNameIs("IdParish")
                                          .Cascade.None()
                                          .SetAttribute("lazy", "false");

                                  }
               );
   }
}

As you can see, we start by indicating that the Address property points to a component and then we need to specify the mappings between the columns of the table and each of the properties of that component class. Nothing really new there, right? Ok, so lets make things more interesting. Suppose we’ve got a collection of components…a good example might be a Contacts property, that returns a collection of Contact objects on the Entity class. That means we could have something like this:

class Entity{
  //previous code
  private ISet<Contact> _contacts;
  public ISet<Contact> Contacts
  {
            get { return  new ImmutableSet<Contact>(_contacts); }
            internal set { _contacts = value;}
  }
  //methods for adding/removing contacts not shown here
}

Now, the interesting part: mapping the properties to the database:

class EntityMapping: ClassMap<Entity>{
  public EntityMapping(){
     //previous code
     HasMany<Contact>(branch => branch.Contacts)
                .AsSet()
                .WithTableName("Contacts")
                .WithKeyColumn("IdEntity")
                .Component(ct =>
                               {
                                   ct.Map(c => c.Kind, "ContactType");
                                   ct.Map(c => c.Value, "Contacto");
                               });
  }
}

If break it apart, we can see that:

  • we have a set that should be kept on a table called Contacts;
  • We’re also creating a foreign key called IdEntity;
  • And then, the important part: we’ve got a collection of components!

I hope that by now I’ve convinced you on using this API. Just to make sure you see what I mean, lets add add some inheritance, ok? Lets suppose we have two new classes (Individual and Company) that expand the previous Entity class:

class Individual: Entity{
  //some properties go here
}

class Company: Entity{
  //it can also be a new type, with no properties
}

Since I wanted to keep both entities on the same table, I’ve ended up writing this on the mapping class:

public class EntityMapping:ClassMap<Entity>{
  //previous code
  DiscriminateSubClassesOnColumn("EntityKind",
                                             (Int32) (EntityKind.Single))
      .SubClass<Individual>()
      .IsIdentifiedBy((Int32) (EntityKind.Single))
      .MapSubClassColumns(e =>
        {
          // code for mapping the properties of derived class
         })
       .SubClass<Company>()
       .IsIdentifiedBy((Int32) (EntityKind.Company))~
       .MapSubClassColumns( e => { } );
}

What are we doing here? First, we’re saying that the table has a column named EntityKind which is used as a discriminator and we’re also setting its default value (I’m casting the enum to integer because that’s the type of my column on the database). Each subclass is introduced by the Sublass method and you’ll also need to pass the values that identify each instance of the derived type (notice the method IsIdentifiedBy call). If you have properties on the derived class, you can map them into the table by calling the MapSubClassColumns method. Notice that even if the new type doesn’t add new properties, you still need to call the MapSubClassColumns method over that subclass (as it’s done in the Company subclass).

Rant Three: Pay attention to the place where you call the DiscriminateSubClassesOnColumn method (it looks like there’s a bug on the way items are compared while ordering the several elements that are maintained internally by the mapping class). In my sample, I had to put it after the Version method. Putting it before resulted in getting the <discriminator> element after the <version>, and that means getting an exception while loading the XML for that class.

By now, we’ve already touched several things you’ll use in a NH application. There’s still one thing missing: how do we load the
definitions from the new classes? One thing you can do is use reflection to load the configuration classes. Here’s some code you can probably reuse for doing that (it’s not really complete; I’m only putting it here to present some concepts):

//get NH Configuration object filled with info that generally
//comes from cfg file
var configuration = GetConfigurationWithDialectConnectionStringEtc();
AddTypesToConfiguration( configuration );
var factory = configuration.BuildSessionFactory();
//from here you can get the ISession you need…

The AddTypesToConfiguration method uses reflection to load the types. It looks something like this:

private void AddTypesToConfiguration(Configuration configuration) {
  //need to get a reference to the assembly where the mapping files are
  var currentTypes = GetAssemblyWithMappingTypes(); 
  var methodsThatReturnXmlDocs = currentTypes
        .Where( existingType => GetMethodForExecution(existingType) != null)
        .Select(existingType => GetMethodForExecution(existingType))
        .ToList();
        //probably could improve this code, but I’ll leave it for you…
        foreach (var method in methodsThatReturnXmlDocs) {
           var doc = method(new MappingVisitor());
           configuration.AddDocument(doc);
        }
}

The GetMethodForExecution type returns a delegate that points to the method that will return the XML document with the mappings:

private Func<IMappingVisitor, XmlDocument>
                                       GetMethodForExecution(Type currentType) {
  //must be a non abstract, non generic class
  //with public instance constructor
  //again, this could probably be improved,
  //but that’s not my objective here…
  if (currentType.IsClass && !currentType.IsAbstract &&
       currentType.GetInterface(typeof(IMapping).FullName) != null &&
       !currentType.IsGenericType && 
       currentType.GetConstructor(Type.EmptyTypes) != null) { 
            var instance = Activator.CreateInstance(currentType);
            var methodInfo = currentType.GetMethod("CreateMapping");
            var method = (Func<IMappingVisitor, XmlDocument>) 
                                  Delegate.CreateDelegate(
                                     typeof (Func<IMappingVisitor, XmlDocument>),
                                     instance,
                                     methodInfo,
                                     true);
             return method;
         }
      return null;
}

All mapping classes implement the IMapping interface and that’s why I’m using that so see if the current type has mapping information. After getting a reference to a valid mapping type, I’ll try to get a reference to its CreateMapping method because that method returns an XmlDocument with the mapping information that will be added to the NH Configuration object.

So that’s it. There are still some more things I could talk about here, but these were the main topics I’ve learnt while building my sample. Even though there are still some bugs, I believe that I will keep using this famework in future projects.

Sep 26

NHibernate and value objects

Posted in C#, NHibernate       Comments Off on NHibernate and value objects

I do love NHibernate but there’ some things that keeps bothering me: value objects. Yes, NH does support it, but it seems like it’s impossible for having inheritance mapping when you decide to use them. There are some scenarios where inheritance makes sense, even when you’re thinking about value objects. For instance, lets think about contacts…You can probably represent a contact through an instance of type Contact, that could look like this (yes, this is a really simple example):

public class Contact{
  private Contact(){}
  public Contact(String value, ContactKind kind ){ … }
  public ContactValue{ get; private set; }
  public ContactKind{ get; private set; }
}

Where ContactKind could be an enumeration that looks like this:

enum ContactKind{
   Phone,
   Email
}

Ok, you could then have an entity which had a Contacts property that, in practice, would be a collection of value objects. This is a supported scenario by NHibernate. However,suppose that you want to have a more explicit API and that’s why you end up changing Contact to:

public class Contact{
  private Contact(){}
  public Contact(String value){ … }
  public ContactValue{ get; set; }
  protected abstract ContactKind{ get; }
}

So that you could introduce a specific type for each kind of contact. Here’s an example for phone:

public class Phone{
  public Phone(String value) : base (value ){ }
  protected override ContactKind{ get{return ContactKind.Phone} }
}

This kind of change will better express my domain and it will let me do further improvements on the base class (for instance,now I can add validation to the constructor so that I always know that the passed in phone number is valid).

Now, unfortunatelly, NH won’t give me any support for mapping this scenario into a table (ok, if there is a way, please let me know). If you want to do that, you’ll have to add an ID to your contact class and you’ll have to transform it into a component (ok, you can mask this so that only NH sees Contact as an entity). Is this such an exotic scenario that I probably shouldn’t be using it? I think not, but I may be wrong…