Fluent NHibernate One-to-One mapping

2020-07-23 05:36发布

问题:

I am having a really hard time exploiting HasOne mapping with Fluent NHibernate. Basically, the class A can have a matching (only one or none) record in the class B.

Please help with the AMap and BMap classes that define the relationships.

Thank you.

public class A
{
   public virtual int Id {get;set;}
   public virtual string P1 {get;set;}
   public virtual string P2 {get;set;}
   public virtual string P3 {get;set;}
}

public class B
{
   public virtual int Id {get;set;}
   public virtual string P4 {get;set;}
   public virtual string P5 {get;set;}
   public virtual string P6 {get;set;}
}

回答1:

To get one-to-one mapping working you will need to add a property of type B to class A and vice versa as per the code below. These references are required in both classes since NHibernate doesn't support unidirectional one-to-one.

public class A
{
  public virtual int Id {get;set;}
  public virtual string P1 {get;set;}
  public virtual string P2 {get;set;}
  public virtual string P3 {get;set;}
  public virtual B child { get; set; }
}

public class B
{
  public virtual int Id {get;set;}
  public virtual string P4 {get;set;}
  public virtual string P5 {get;set;}
  public virtual string P6 {get;set;}
  public virtual A parent;
}

Then in the fluent mappings you will need to add the following

public AMap()
{
  /* mapping for id and properties here */
  HasOne(x => x.child)
      .Cascade.All();
}

public BMap()
{
  /* mapping for id and properties here */
  References(x => x.parent)
      .Unique();
}

Please note that the one-to-many mapping in BMap is marked as Unique. This is used to create a unique column constraint if you use NHibernate to generate the DB schema.

To create a new record you would then write something like:

    using (var transaction = session.BeginTransaction())
    {
        var classA = new A();
        classA.child = new B() { parent = classA};

        session.Save(owner);
        transaction.Commit();
    }

Finally one caveat, the current release of NHibernate, 3.4, doesn't support cascade deletes of orphaned one-to-ones. See here for the bug report. This means if you write something like session.Delete(classA); then the associated class B record won't be automatically deleted.