views:

395

answers:

2

Hi,

Is it possible to set the default value of a property in NHibernate? Here is the scenario:

I have a self join table Category. The class and table structure are as follows:

Category
int Id
string Name
Category ParentCategory

Category
int Id not null
varchar Name not null
int ParentCategoryId not null

If a category has no parent, the ParentCategoryId must be 0.

How do I do this? TIA.

A: 

If nHibernate is enforcing this relationship I don't believe you can make it form an invalid relationship. I'd create a dummy parent record 0 in the database and just assign everything to that.

Spencer Ruport
Thanks Spencer for the idea, however we can't do that since we are only integrating to an existing application.
A: 

If the ParentCategoryId is not constrained by a foreign key, then you can have in your code ... something like :

class Category{
   ....

   public static Category NoParent{
     get{ return new Category{Id = 0}; }
   }


   ....
}

and now, instead of setting to null, just set it to NoParent. Or in the setter of ParentCategory, if value is null, then set it to NoParent.

This is basically Spencer Ruport's ideea :P

sirrocco
@sirrocco, how would you reflect that in the mappings?
by the way, I already tried that. Assigning a category instance with id = 0 to the parentcategory property, but to no avail.
What do you mean by no avail ? was it throwing an error or what ?
sirrocco