5

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.

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
RiskX
  • 561
  • 6
  • 20
  • I think it's best if you didn't ask for finely tuned answers including "no fluent mapping solutions" - since as a reader of this question, who uses fluent mapping, I would benefit greatly from the answer including it. The answers aren't exclusively for you – PandaWood May 03 '17 at 06:11

1 Answers1

3

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);
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • 1
    Fluent Nhibernate: Map(x => x.Property) .Not.Update(); – Th3B0Y Aug 31 '16 at 04:58
  • `.ReadOnly()` is something else. It ensures you only read data from the DB. It's used to get data generated directly by the DB (and should never even be inserted from outside), normally. – Th3B0Y Sep 01 '16 at 00:20
  • @Th3B0Y **NO**. Firstly, I would strongly discourage you from learning or even using obsolete and deprecated fluent.. But if you try to understand it - you should learn it carefully. Try to avoid mixing expectations and facts *(which in fact - a different naming in fluent - has caused/brought)*. Mapping is working exactly as I say: ***ReadOnly method ... is just a shortcut for setting both `.Not.Insert()` and `.Not.Update()`.*** [read more](http://notherdev.blogspot.cz/2012/01/mapping-by-code-property.html). Hope it could help you a bit... and ask a question if you want even more ... ;) – Radim Köhler Sep 01 '16 at 05:31
  • I didn't understand that from what you wrote before, but it still means what I said. It means the property won't be written anywhere else than the DB or something else that is allowed to write to it. – Th3B0Y Sep 02 '16 at 09:56