Search code examples
nhibernatenhibernate-mapping

NHibernate formula with scalar function


I have a property in my object that was mapped using formula, it is a dynamic value which is given by a scalar function that was defined in my db

here is my mapping:

<property name="StatusId" type="Int32" formula="(SELECT dbo.FN_GET_STATUS(ID))"/>

This property gives me a correct value when I call GetById function from session factory. However when I Save a newly created object, I dont get a value for the property. Is there a way i can fix it or am i doing something wrong?


Solution

  • Try to use built-in setting generated="insert"

    5.1.10. property

    <property
        name="propertyName"                 (1)
        ...
        generated="never|insert|always"     (8)
    

    ...(8) generated (optional - defaults to never): Specifies that this property value is actually generated by the database. See the discussion of Section 5.5, “Generated Properties”.

    5.5. Generated Properties

    Generated properties are properties which have their values generated by the database. Typically, NHibernate applications needed to Refresh objects which contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to NHibernate. Essentially, whenever NHibernate issues an SQL INSERT or UPDATE for an entity which has defined generated properties, it immediately issues a select afterwards to retrieve the generated values.