views:

1438

answers:

1

I have a very simple Country entity which I want to cache. This works perfectly, but I want a clone version of the cached instance to be returned or be made read-only to prevent developers from changing the state of it.

How would I achieve this? I tought that the Fluent Readonly() method would enforce this, but it's not the case.

Sample Fluent Mapping:

        Id(x => x.Id);
        Map(x => x.Name).WithLengthOf(50).Not.Nullable().Unique();
        Map(x => x.IsoCode).WithLengthOf(10).Not.Nullable().Unique();
        HasMany(x => x.States).Cascade.None().LazyLoad();          
        Cache.AsReadOnly();

My unit tests clearly indicates that the entities are cached and that the same entity is returned on subsequent gets, but I want the object to be immutable once it's loaded from the persistent store.

Thanks!

+2  A: 

If you want instances of your class to be immutable (in the sense that it's impossible to modify object instances), then you'll need to write your class according - it's nothing to do with NHib or Fluent NHib. As an example, map NHib onto private fields or private property setters and only expose property getters publicly.

With NHib it is possible to specify "mutable=false" on your class mapping (not sure how to do this with FNH, sorry). This doesn't make the object immutable at runtime, but it does inform NHib not to check for inserts, updates and deletes against these entities.

John Rayner