我有 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 值加入另一个表。有人可以指导我如何使这个东西起作用吗?
最佳答案
由于您正在寻找一对一的关系,因此您的映射需要明确这一点。
首先,Content 需要了解其父文章。如果不想公开该属性,可以使用 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/
关于c# - 具有相同主键的 FluentNHibernate 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16688120/