1
votes

I have a database table having one of the column as nullable . I want to save an entity through NHibernate mapping which saves some default value in case of entity member being null. Entity:

public class Person
  {
    public virtual int PersonId { get; set; }
    public virtual string Name { get; set; }
    public virtual int ?Age { get; set; }
  }

Person.hbm.xml file :

Now, when I am trying to save the entity with null value for Name and Age, I want the default value to be saved in database table. Is there any way for it? Please answer..

2
Did you forge the xml file?Qben

2 Answers

1
votes

Yes, there is a very simple way to it

public class Person
{
    public Person(){
         Age = 15; // default value
    }

    public virtual int PersonId { get; set; }
    public virtual string Name { get; set; }
    public virtual int Age { get; set; }
}
1
votes

You have two ways to insert default values.

a) define it on the database level. This will add a constraint on your table which inserts a default value. You can do this via mapping if you generate the schema from your mapping or define it in your database scripts...

The only important thing you have to do in your mapping is to instruct nhibernate not to try to insert null values for properties which are null...

This can be achieved by setting DynamicInsert for the mapping. If you want to have the same mechanism for updates, also define DynamicUpdate...

Here are some examples for fluent nhibernate:

public class SomeMap : ClassMap<Something>
    public PostMap()
    {
         ...
         DynamicInsert();
         Map(p => p.StringProperty).Default("N'something'");

         Map(p => p.SomeInt).Default("1");
         ...

As you can see you have to define the values in SQL notation! Otherwise nhibernate will throw some exceptions creating the schema...

This also works for nullable columns of course.

b) Simply use the constructor of your entity.