views:

97

answers:

3

I'm starting a new project and plan on using nhibernate. I'm struggling with whether or not I should keep my domain model clean of persistence information by leaving out foreign keys. I keep feeling like some of my "model" isn't really necessary and that performance is going to be an issue. For example:

In my db I have the following table:

Posting
    Id
    StatusId
    ...

Which has an FK relationship with this table:

PostingStatus
    Id
    Name

In my model I've defined 2 classes:

class Posting
{
    virtual int Id { get; set; }
    virtual PostingStatus Status { get; set; }
    // ..
}

class PostingStatus
{
    virtual int Id { get; set; }
    virtual string Name { get; set; }
}

Does PostingStatus belong in my model? and in cases where I know the FK ahead of time, like updating a posting after a submit, isn't it a pretty heavy performance hit (or just useless work) to have nhibernate fetch a PostingStatus instance instead of just setting a FK?

I'm pretty sure this issue has been discussed before but I keep finding bits an pieces of the discussion that have shotty relevance. Thoughts or resources on this issue would be greatly appreciated.

+2  A: 

If the Domain Model requires relationships to be enforced then you need Foreign Keys.

Don't worry about performance until you actually have a performance problem.

Mitch Wheat
+1  A: 

What Mitch said. NHibernate was put together by people who thought about these issues thoroughly. Do what's right, worry about optimization when and if you have a problem.

(nhibernate's probably going to be fetching the posting sttaus from cache, anyway.)

Besides, nhibernate, depending on how you set it up, may need FK constraints to map your database to your objects.

If PostingStatus is an domain entity, you should keep it. If it's not, remove it for that reason, not in an attempt to prematurely optimize.

tpdi
+1  A: 

In this very special case you might actually replace the entity PostingStatus with Enum. If you specify values for your enum properly they can map to a table and be enforced by FK.

And NH will not 'just cache' stuff. I'd suggest using 2nd level cache with lazy loading of PostingStatus heavily for this kind of situations.

Rashack