2

I was using Fluent NHibernate as mapping mechanism for my NHibernate projects. But when it came to NHibernate 3.2, I realized that it has mapping by code built in, and no Fluent Nhibernate releases will be published for NHibernate 3.2.

I encountered a question when I want to set a default value for a entity property, I didn't find the API to do that. Can anybody give some advice?

Liu
  • 645
  • 2
  • 8
  • 16

3 Answers3

7

I haven't used mapping by code yet, but the NHibernate.Mapping.ByCode.Impl.ColumnMapper class has a method Default(object defaultValue). This issue in NHibernate's JIRA, apart from pointing out a caveat, shows how to use it:

mapper.Class<MyDomainObject>(map => map.Property
    (s => s.TermService, 
        pm => pm.Column(cm => cm.Default("'my default value'"))));

Is this what you were looking for?

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
5

I found this code. May help u.

        Property(x => x.Property, m =>
        {
            m.Column("columnName");
            // or
            m.Column(c =>
            {
                c.Name("columnName");
                c.Default("defaultValue");
                c.SqlType("varchar(max)");
                c.Length(SqlClientDriver.MaxSizeForLengthLimitedString + 1);
                c.NotNullable(true);
                c.Check("len(columnName) > 1");
                c.Precision(2);
                c.Scale(2);
                c.Index("column_idx");
                c.Unique(true);
                c.UniqueKey("column_uniq");
            });
            m.Type<string>(); // or IUserType
            m.Update(true);
            m.Insert(true);
            m.Formula("arbitrary SQL expression");
            m.Access(Accessor.Field); // or Accessor.Property or Accessor.NoSetter
            // or
            m.Access(typeof(CustomAccessor));
            m.OptimisticLock(false);
            m.Generated(PropertyGeneration.Insert); // or PropertyGeneration.Always or PropertyGeneration.Never
            m.Lazy(true);
        });
xwing
  • 111
  • 2
  • 4
  • In the future, it is very helpful if you can explain exactly how the code you provide works - the more details, the better! –  Feb 01 '14 at 17:11
  • I recognize this code, it's from someone else's blog. http://notherdev.blogspot.ca/2012/01/mapping-by-code-property.html – Nick Albrecht May 16 '16 at 21:23
1

When using a DataBase first, setting the default value in the mapping doesn´t work. You have to tell the nhibernate to work with the DataBase Default value. To do that, first you set the default value for the column in your Database.

After that, you tell the nhibernate mapping to ignore the column at insert by doing this:

Property(x => x.PropertyName, map =>
        {   map.Insert(false);
            map.Column("FL_COLUMN");                
            map.NotNullable(true);
        });
Daniel
  • 2,780
  • 23
  • 21