Mapping a read-only property with no setter using Fluent NHibernate

人走茶凉 提交于 2019-12-05 11:41:13
James Gregory

ReadOnly instructs Fluent NHibernate to not look for changes on this property, this does not equate to a read-only property in compiler-world. Your property isn't read-only in NHibernate's eyes because you're expecting it to be populated from your database. What you need to do is tell NHibernate that it should access the value of that property through a private field with the same name (lowercased) as the property.

Map(x => x.LastUpdate)
  .Access.Field();

There are several alternatives to using Field, which one you use will depend on how you name your private fields.

As far as NHibernate goes, you can map to a field, i.e member variable so Nhibernate can access the member variable directly. So you can create a member variable like _lastUpdate that can be mapped directly. Nhibernate will now have a variable to use and you can control the value separately in your getter because NHibernate will no longer use the property getter. It will save the value, and retrieve it too, but the retrieved value should not matter because as soon as you access through your getter you can recalculate it. Ditto for private variables with no getters or setters.

In a regular hbm you would just map access=field. Everyone does it. Apparently Fluent is not a simple. I don't use Fluent ...

EDIT ...

find whatever the seemingly always moving target for mapping private backing fields is in your version and use that ...

Just add an empty private setter to your class:

        private set { }

I also add an attribute and a comment to document my intent (and make ReSharper happy):

        [UsedImplicitly]
        // ReSharper disable once ValueParameterNotUsed
        private set { }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!