![](/img/trans.png)
[英]FluentNhibernate mapping of two tables oneToMany using unique instea of primary key in mapping
[英]FluentNHibernate Mapping with same primary key
我有2張桌子,像這樣:
TABLE ARTICLE
Id int NOT_NULL PK
Title nvarchar(50) NOT_NULL
TABLE CONTENT
Id int NOT_NULL PK
content nvarchar(MAX) NOT_NULL
remarks nvarchar(200)
因此,每篇文章的內容都將具有與文章pk ID相同的pk ID,然后我就創建了這樣的域類:
public class Article {
public virtual int Id {get; set;}
public virtual string Title {get; set;}
public virtual Content Content {get; set;}
}
public class Content {
public virtual int Id {get; set;}
public virtual string content {get; set;}
public virtual string remarks {get; set;}
}
我嘗試像這樣映射這些類:
public class ArticleMap : ClassMap<Article>
{
public ArticleMap()
{
Id(x => x.Id);
Map(x => x.Title);
Reference(x => x.Content).ForeignKey("Id");
}
}
public class ContentMap : ClassMap<Content>
{
public ContentMap()
{
Id(x => x.Id);
Map(x => x.content);
Map(x => x.remarks);
}
}
我確實將數據讀取到表中,但最終出現NHibernate.ObjectNotFoundException
。 在我的情況下,我應該如何映射沒有外鍵的類,而僅基於相同的PK Id值加入另一個表。 有人可以指導我如何使這件事起作用嗎?
由於您正在尋找1:1關系,因此您的映射需要明確說明。
首先,內容需要了解其父條款。 如果您不想公開該屬性,則可以使用protected internal
屬性,也可以在映射中使用“ Reveal
。 請注意,在這些情況下,您將需要一個接受Article的構造函數和一個用於NHibernate的空構造函數。
public class Content {
public virtual Article { get; set; }
//other properties
}
然后,您的映射就像
public class ArticleMap : ClassMap<Article>
{
public ArticleMap()
{
Id(x => x.Id);
Map(x => x.Title);
HasOne(x => x.Content).Cascade.All();
}
public class ContentMap : ClassMap<Content>
{
public ContentMap()
{
Id(x => x.Id).GeneratedBy.Foreign("Article");
HasOne(x => x.Article).Constrained().ForeignKey();
Map(x => x.content);
Map(x => x.remarks);
}
}
另請參閱: http : //marcinobel.com/index.php/fluent-nhibernate-mapping-one-to-on-relation/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.