views:

397

answers:

3

I'm not an advanced NHibernate user, so this may be somewhat important, and I just didn't discover it yet.. but what the heck.

Consider the class:

public class House
{
    public int Id { get; set; }

public ISet<Room> Rooms
{
    get;
    set;
}

}

When specifying NHibernate Set element it's not enough to write:

<set name="Rooms" />

Instead I have to write at least:

<set name="Rooms">
  <key column="RoomId"/>
  <one-to-many class="Room"/>
</set>

This seems to be a violation of DRY principle. If it's a Set the default should be that it's a one-to-many relationship. The class should be inferred from generic type of the collection and as the key column, primary key of collection element's class should be used.

This seems to me like a reasonable defaults. Why then, NHiberbate is not smart about it, and requires me to type these extra 3 lines?

A: 

You might have a look at Fluent NHibnernate. Their DSL is inspired by DRY.

Edit: Sorry should have read more carefully...

Regarding your example, Fluent NHibernate would allow you to express the mapping as:

HasMany(x => x.Rooms);

However, the HasMany (or One-To-Many) relationship is mapped to IList. I am not sure if this can be customized further (let Fluent map to ISet as default). But either way it is less repetitive than the standard mapping declaration.

Here are some examples for declaring mappings: Fluent NHibernate Wiki.

olli
I'm aware of FluentNHibernate. That's however not an option for me, and it still does not answer the question.
Krzysztof Koźmic
A: 

What if you do not use a generic collection ? If I'm not mistaken NHibernate only supports generics as from version 1.2; so in previous versions type inference was definetly not possible.

What if you use a legacy DB, in which the primary ID is not used as the foreign key in the related table ?

Frederik Gheysels
Then I would not go with the defaults. However having these values as defaults would make sense IMHO. Even if in .NET 1.1 time that made sense, it does not anymore. So is it a leftover?
Krzysztof Koźmic
+1  A: 

because, I would think, that when NH creates the proxies based on the mappings it would take longer to have to also go through your assemblies and, via reflection, work out what it needs to do. This would add to the startup time of the NH factory.

Don't forget, it's an object to relational mapper. You'll need at least one of the extra nodes (the key) to tell it what the DB key it needs to work with is. This allows you to be as flexible as you wish when mapping to the DB and not be hardwired into a default.

Does it break DRY? Possibly. Do I care in this instance? No not really.

Graham