21

I have a few classes that read from very delicate tables, which is why I want them to be used by NHibernate as "ReadOnly". Establishing .ReadOnly() on each field map is really sloppy, and I'm not sure I trust it. How do I setup a class to be entirely readonly, as I can easily do with traditional XML mappings?

Edit: The answer does work. I expected it to throw an exception if I tried to save over a ReadOnly() object, but it just silently does so.

Thanks.

rebelliard
  • 9,592
  • 6
  • 47
  • 80
  • @kaptan: I will edit my comment on the answer. It does work. I just expected it to throw an exception, but it just silently ignores any changes. – rebelliard Sep 13 '10 at 18:37

2 Answers2

37

With Fluent NHibernate, it's as simple as:

class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        ReadOnly();

        // Mappings
    }
}
Bryan Menard
  • 13,234
  • 4
  • 31
  • 47
16

The ReadOnly() property actually does NOT work like you would expect. Using this property makes sure that the objects that you retrieve are read-only, so you cannot UPDATE them. However, it does NOT prevent the creation of new records or even the deletion of existing records in the database!

Roger Frehen
  • 161
  • 1
  • 2
  • 1
    Hmm, hadn't noticed that, which is crazy! I guess a mixture of readonly and protected constructor would work. – rebelliard May 11 '12 at 14:20
  • 1
    I think "Immutable" is a better name for it. – Mark Broadhurst May 22 '15 at 15:05
  • `ReadOnly` is the Fluent naming, it seems they have deemed it better than the original NHibernate naming, [`mutable="false"`](http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-class). Maybe in their context, where they have defined `ReadOnly`on properties as a shorthand for `insert="false" update="false"`, but in my view this is an unfortunate naming for class and collection mutability. – Frédéric Jun 15 '17 at 13:46