Saturday, October 22, 2011

FluentNHibernate: How to globally set id's of all entities as assigned?

Sometimes you have a model in which all entities identifiers are controlled externally from your database - i.e. they are from external systems or you have some kind of sequence generator running separately from the database. In this case, when using Fluent NHibernate, we can turn off generating identity values in database in every mapping using:

Id(x => x.Id).GeneratedBy.Assigned();

But for larger models this may be a bit repetitive. And again, this is where conventions are to help. We can implement very simple convention, that will cover all our entities:

public class AssignedIdConvention : IIdConvention
{
public void Apply(IIdentityInstance instance)
{
instance.GeneratedBy.Assigned();
}
}

And then register it in Fluent NHibernate configuration like this:

Fluently.Configure()
.Mappings(...)
.Conventions.Add<AssignedIdConvention>()

That's all!

But be advised that in general, managing identity values on our own is not the best practice and there is only one use case I can think of, when it is necessary - when we use external data sources (i.e. when our database contains data imported from other databases, like global customers database or authorization system). Note that using natural keys, like Tax Identification Numbers or similiar, can be misleading, as the real world can surprise us in many ways and we'll have no way to handle user without that number or two users with duplicate numbers (and this may happen for sure).

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.