Using NHibernate.Generics & Active Record
I modified my code today to use NHibernate.Generics.
So far I’m very pleased with the simplicity it brings to my code. However,
there are some things that I discovered:
- Always initialize the EntitySet
& EntityRef in the default constructor, and make sure that all your
constructors call to the default constructor.
- Always use EntityRef when you
are connecting persistent objects, even if currently the connection is one
sided. Sometime in the future you may need to make the connection
bidirectional and it might save you some pain. Actually, this advice is
wrong. The problem is not switching from normal property access to
EntityRef. That is quite simple; the problem is that it may be confusing
to have some EntityRef and some domain objects. If everything is an
EntityRef, there are no problems, it’s clear that there is no
connection since the EntityRef’s change & add delegates are
empty.
- Do not use the EntityRef’s
constructor overload which pass an initial object, this overload is going
to go away, and it’s bad idea to use it since then the delegates are
not called on it.
I added the ability to specify a custom access strategy to Active Record and
now you can do things like this:
[HasMany(typeof (Post), "PostId", "Posts", Inverse=true,
CustomAccess = Generics.Access,
RelationType = RelationType.Set)]
public ICollection<Post> Post
{
get { return post; }
}
As you can see, it’s one big ass attribute, but you
specify it once, and then just forget about it.
Some notes about it:
- Generics.Access – This is
a static class with a const field that contains “NHibernate.Generics.GenericAccessor,
NHibernate.Generics”. It makes the code much more readable, IMO.
- RelationType – Active Record
can no longer guess at the type of the relation, so you need to tell it
explicitly.
Comments
Comment preview