views:

294

answers:

1

How can a domain object include a property that calculates a value from other database mapped properties so that the calculated property can be used in both the domain object instance and the db level by nhibernate.linq.

I would like to be able to use the property when working with the object directly:

Console.WriteLine(Entity.Calculated.ToString());

And when working with nhibernate.linq

var q = from e in session.Linq<Entity>()
                where e.Calculated > 0
                select e;
+2  A: 

You need to duplicate the logic in the class and the mapping. Here's an example:

Class:

public class Invoice
{
    public virtual int Id { get; protected set; }
    public virtual decimal Amount { get; set; }
    public virtual decimal Paid { get; set; }
    public virtual decimal Balance
    {
        get { return Amount - Paid; }
    }
}

Mapping:

<class name="Invoice">
    <id name="Id">
        <generator class="hilo"/>
    </id>
    <property name="Amount"/>
    <property name="Paid"/>
    <property name="Balance" formula="Amount - Paid" access="readonly"/>
</class>

Now you can use Linq and query on Invoice.Balance

Diego Mijelshon
Perfect! Do you know if there is a way to use a linq expression to inject the formula? Expression<Func<Invioce, decimal>> exp = i => i.Amount - i.Paid;
Inject where? keep in mind that "Amount - Paid" in the formula is referring to the fields, not the properties.
Diego Mijelshon
I would like to write a lambda 1 time and have the property use the expression by calling return expression.compile().invoke(invoice); and also have nhibernate use the expression in place of the formula based on sql syntax. This way I only write the algorithm 1 time. I think I have lead myself to a new question. I'll post a link to new question once I determine how to ask it.
new question http://stackoverflow.com/questions/2233341/nhibernate-linq-use-lambda-expression-in-place-of-formula-attribute-on-mapping