Reputation: 544
In playing around with Fluent NHibernate, I've tried to implement a save method in the entity object. Is this a hands-down horrible idea? It seems that this would be the perfect place to interface between my presentation and database but the fact that I need to set the virtual keyword on everything makes me think this was never intended to be used like this.
Entity:
public class MyTable : BusinessObject
{
#region Properties
/* ... */
#endregion
public virtual void Save()
{
var sf = CreateSessionFactory();
using (var s = sf.OpenSession())
{
using (var t = s.BeginTransaction())
{
s.SaveOrUpdate(this);
t.Commit();
}
}
}
}
Base class:
public abstract class BusinessObject
{
protected static NHibernate.ISessionFactory CreateSessionFactory()
{
return FluentNHibernate.Cfg.Fluently.Configure()
.Database(...)
.Mappings(...)
.BuildSessionFactory();
}
}
Upvotes: 0
Views: 582
Reputation: 52735
As it's stated, it's a very bad idea.
But what you are trying to do is actually a well known pattern: Active Record
The project I've linked to is based on NHibernate and it already has a base class with Save
and other methods implemented
Upvotes: 3
Reputation: 15303
I agree with @AlexCuse.
Another thing that's missing from the implementation above too is the fact that you can't save multiple business objects or different types of business objects in the same transaction which is often necessary.
Upvotes: 2
Reputation: 18306
I think this is a bad idea. It seems convenient now but if your domain grows to even a medium size it could get quite messy.
It may not end up as bad with NHibernate, but we have a domain model using a similar approach and it ended up WAY too coupled to our ORM. This made it exceedingly difficult the first time we tried to move off of our ancient, terrible ORM. It can make testing interesting also if you aren't careful. A lot of this had to do with the fact we had to generate our own lazy-loading code, so your mileage may vary, but I think it really pollutes your domain layer. It's not that much more effort to implement a repository or queryable pattern and it will keep your domain model much cleaner.
aside: you don't want to create a session factory each time - you want to create it once for the application lifetime, and then create a session each time you need it (or potentially less often - think a bit about the idea of a Unit of Work, and if you're confused on session vs session factory I wrote this in response to a similar question a while back)
Upvotes: 4