Fluent NHibernate One-to-One mapping

余生颓废 提交于 2020-01-01 16:06:02

问题


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.



来源:https://stackoverflow.com/questions/15724562/fluent-nhibernate-one-to-one-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!