[英]Fluent NHibernate One-to-One mapping
I am having a really hard time exploiting HasOne mapping with Fluent NHibernate. 我很难用Fluent NHibernate开发HasOne映射。 Basically, the class A can have a matching (only one or none) record in the class B. 基本上,A类可以在B类中具有匹配(仅一个或没有)记录。
Please help with the AMap and BMap classes that define the relationships. 请帮助定义关系的AMap和BMap类。
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;}
}
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. 要使one-to-one
映射工作,您需要根据下面的代码将类型B
的属性添加到类A
,反之亦然。 These references are required in both classes since NHibernate doesn't support unidirectional one-to-one. 这两个类都需要这些引用,因为NHibernate不支持单向一对一。
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
. 请注意, BMap
的一对多映射标记为Unique
。 This is used to create a unique column constraint if you use NHibernate to generate the DB schema. 如果使用NHibernate生成数据库模式,则用于创建唯一列约束。
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. 最后一点需要注意,当前版本的NHibernate 3.4不支持逐级删除孤立的一对一。 See here for the bug report. 请参阅此处获取错误报告。 This means if you write something like session.Delete(classA);
这意味着如果你写了session.Delete(classA);
then the associated class B record won't be automatically deleted. 那么关联的B类记录将不会被自动删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.