Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a column multiple times in Nhibernate

I have for example an entity. With the following properties:

public class Entity
{
   public int CustomerId { get; set; }
   public Customer { get; set; } 
}

How can I map the CustomerId twice. Once for the int property and once for the many-to-one relationship ?

<many-to-one name="Customer" column="[CustomerId]" class="Customer"/>
<property name="CustomerId" column="[CustomerId]" type="Int64" />

Just this, doesn't work. I've already tried, making them readonly but no success.

like image 611
Preben Huybrechts Avatar asked Sep 02 '25 10:09

Preben Huybrechts


2 Answers

One of them should be mapped as readonly (inser/udpate false), and referenced as formula

<many-to-one name="Customer" column="[CustomerId]" class="Customer"/>
<property name="CustomerId" formula="[CustomerId]" type="Int64" insert="false" update="false" />

Then it should be working correctly. Both properties then can be used for Select, Where... order by

like image 135
Radim Köhler Avatar answered Sep 05 '25 10:09

Radim Köhler


You don't need to map CustomerId, you can access it through Customer.CustomerId. If you're using lazy loading, CustomerId will be populated in the proxy object so it's always available without triggering an additional select.

If you absolutely have to expose it, expose it as a nullable read only property:

   public Customer { get; set; } 
   public int? CustomerId
   {
       get { return Customer == null ? (int?)null: Customer.CustomerId }
   }
like image 28
Jamie Ide Avatar answered Sep 05 '25 09:09

Jamie Ide