8

Let's say I have the following entity:

public class CalculationInfo
{
    public virtual Int64 Id { get; set; }

    public virtual decimal Amount { get; set; }

    public virtual decimal SomeVariable { get; set; }

    public virtual decimal SomeOtherVariable { get; set; }

    public virtual decimal CalculatedAmount
    { 
        get
        {
            decimal result;

            // do crazy stuff with Amount, SomeVariable and SomeOtherVariable

            return result;
        }
    }
}

Basically I want to read and write all of the fields to my database with NHibernate with the exception of CalculatedAmount, which I simply want to write and not read back in.

Every similar issue and corresponding answer has dealt with specifying a backing store for the value, which I won't have in this scenario.

How can I accomplish this using Fluent NHibernate?

Thanks!

UPDATE: Here's what I've tried, and the error it leads to:

Here's my mapping for the property...

Map(x => x.CalculatedAmount)
      .ReadOnly();

And the exception it yields...

Could not find a setter for property 'CalculatedAmount' in class 'xxx.CalculationInfo'

Brandon Linton
  • 4,373
  • 5
  • 42
  • 63

3 Answers3

5

I figured out that the way get this mapping working in Fluent NHibernate is to simply add the Access Property:

Map(x => x.CalculatedAmount).Access.ReadOnly();
Ferry de Boer
  • 71
  • 1
  • 5
2

I don't use Fluent, but in the mapping a persisted property with no setter is mapped with access="readonly", so look for something like .Readonly()

(Readonly is from the model perspective; the value is written to the DB and used in dirty checks)

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • I've updated my answer to address that...it was one of the first things I came across, but I still ended up with the exception above. Can you think of a setting in NHibernate that would block this from working? – Brandon Linton Jun 23 '10 at 14:21
  • Can you export the XML that FluentNH generates? – Diego Mijelshon Jun 23 '10 at 16:59
0

Looks like it's a calculated value. If you can calculate this value at any given time, then why store it at all?

Steven Evers
  • 16,649
  • 19
  • 79
  • 126
  • Great question...the short answer is non-repudiation. Even if my method of calculation changes, I can always point to what was calculated at a given point in time / correlated to an action. – Brandon Linton Jun 23 '10 at 02:14
  • @Brandon Linton: Fair enough. +1. Is there any reason why a private backing field is undesireable, or is it more of an issue of aesthetics? – Steven Evers Jun 23 '10 at 02:24
  • it would just never end up getting used...the calculation should be performed every time, since the variable factors can change at any time. – Brandon Linton Jun 23 '10 at 14:15
  • I have the same situation. I need to persist a read-only, derived value for reporting purposes. – Rob Kent Nov 30 '10 at 14:44