简体   繁体   中英

How to create a one-to-one mapping in NHibernate using Mapping Attributes

I am trying to create a one-to-one mapping in my application, I tried several samples that I have found in Stackoverflow and other places, but no success so far.

I have a Order class and a reservation class. Several orders can exist without a reservation, but reservations always has to have an order.

My plan is to put the FK in the reservation table and the code is as follow:

  class Order
  {
     ... 
     [OneToOne(Cascade = "all-delete-orphan")]        
     public Reservation Reservation
     {
        get;
        private set;
     }
  }

And class reservation:

 class Reservation
 {
    ...
    [ManyToOne(Column = "order_id", NotNull=true, Unique=true)]        
    public Order Order
    {
        get;
        set;
    }
 }

This works nicely, but when I try to remove an order:

session.Delete(myOrder);
session.FlushSession();

I get an FK violation exception due to the reservation FK being null, but I was expecting the reservation to be automatically removed due to the Cascade parameter.

Any suggestions?

Thank you

I have found the problem: when an order was loaded it was trying to lookup an reservation using a clause like: "WHERE order.id = revervation.id", but actually it needed to check the FK in reservation table: "WHERE order.id = reservation.order_id"

Because of this, the reservation was never properly loaded and when an order was removed, no reservation was removed, the result was that the order was removed from the db and when flush was issued, the FK constraint was violated because the reservation was still there.

To fix the issue, I changed the Order code to:

[OneToOne(Cascade="all-delete-orphan", ForeignKey="none", PropertyRef="Order", Lazy=Laziness.Proxy)]        
    public Reservation Reservation
    {
        get;
        private set;
    }

Note the "PropertyRef" parameter.

Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM