简体   繁体   English

与Fluent NHibernate一对一或零关系

[英]One to One or Zero relationship with Fluent NHibernate

Given two tables: 给定两个表:

 ___________
|Table1     |
|-----------|
|Id         |
|___________|
 ___________
|Table2     |
|-----------|
|Id         |
|Table1_Id  |
|___________|

Where Table2 record doesn't neccesserily have to exist (ie the relationship is One{Table1}-to-OneOrZero{Table2} ). Table2记录不一定必须存在的地方(即,关系是One {Table1} -to-OneOrZero {Table2} )。

I need to be able to Save and Retrieve data from both tables using a parent class, which is mapped to Table1. 我需要能够使用父类(映射到Table1)从两个表中保存和检索数据。

The entities are as follows: 实体如下:

public class Table1
{
   int Id {get; set;}
   Table2 Table2 {get; set;}
}
public class Table2
{
   int Id {get; set;}
}

...I've created the mappings as follows: ...我创建了如下映射:

public class Table1Map
{
   this.Id(x => x.Id);
   HasOne(x => x.Table2).Cascade.All();
}

public class Table2Map
{
   this.Id(x => x.Id);
}

...which works fine for reading but not writing the data, because it tries to insert NULL into Table2.Table1_Id column instead of taking it from Table1.Id property. ...这对于读取但不写入数据非常有效,因为它尝试将NULL插入Table2.Table1_Id列,而不是从Table1.Id属性中获取。

Is there a way to make this work for inserts without having to create a bi-directional reference, ie without Table1 property on Table2 class ? 有没有一种方法可以使此插入工作而不必创建双向引用,即在Table2 class上没有Table1属性?

I have recently come across this question in SO. 我最近在SO中遇到了这个问题。 As far as relationship goes, as already mentioned by @Hacked it can't be HasOne because they are not sharing a common primary key. 就关系而言,正如@Hacked所提到的,它不能是HasOne,因为它们没有共享公共主键。 Consider using HasMany (not really sure) and missing part for unidirectional relationship is Not.KeyUpdate 考虑使用HasMany(不确定),单向关系缺少的部分是Not.KeyUpdate

public class Table1Map
{
   this.Id(x => x.Id);
   HasMany(x => x.Table2)
   .Not.KeyUpdate() <--here
   .Cascade.All();   
}

Below are the reference links 以下是参考链接

NHibernate configuration for uni-directional one-to-many relation NHibernate配置用于单向一对多关系

NHibernate still issues update after insert 插入后,NHibernate仍然发出更新

Normally, you'd just uses References rather than HasOne . 通常,您只使用References而不是HasOne See I think you mean a many-to-one, sir . 瞧, 我想您的意思是一对多,先生

Article summary: HasOne , or one-to-one relationship, is specifically for a relationship where the two tables share a primary key. 文章摘要: HasOne或一对一关系专门用于两个表共享一个主键的关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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