Exclude property from INSERT command in nhibernate

2019-02-27 08:47发布

问题:

I have an entity with a property which I wish to be readonly - meaning that when I insert this entity to the DB, SqlServer will generate the property's value automatically so I need nhibernate to ignore this property when executing the INSERT command but retrieve it when selecting the entity.

Important note: this property isn't ID! I don't want NHibernate to initialize it using generator, SqlServer will do it by itself.

And another note: I use configuration mapping so no fluent mapping solutions please.

回答1:

That functionality is supported. There are two attributes:

<property name="GeneratedBySql" insert="false" update="false" />

The same could be applied even for reference mapping

<many-to-one name="ReferenceGeneratedBySql" insert="false" update="false" />

If we want to use Mapping-by-Code we do have the same in places, see:

Mapping-by-Code - Property (by Adam Bar)

Snippet cited:

Property(x => x.Property, m =>
{
    m.Column("columnName");
    ...
    m.Update(false);
    m.Insert(false);