流利的NHibernate一对多的单向映射 [英] Fluent NHibernate one to many uni-directional mapping

查看:97
本文介绍了流利的NHibernate一对多的单向映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Post和Comment类,他们有一对多的关系,Post有一个注释列表。我怎么能把这个映射为与Fluent NHibernate的单向关系,因为评论不需要知道它的父邮件?目前,这是我的映射评论:

  Id(x => x.Id); 
Map(x => x.Body);
引用(x => x.User);

和Post:

  Id(x => x.Id); 
Map(x => x.Title);
HasMany(x => x.Comments)
.Inverse()
.WithKeyColumn(PostId)
.Cascade.AllDeleteOrphan();

这不起作用,因为当我尝试使用新添加的Comment保存Post实例时,外键在注释(PostId)留空。当然,注释不能用NULL PostId保存。我尝试删除.Inverse()子句,但这也不起作用。

解决方案

NHibernate不支持这个映射当你有一个非空的约束你的外键。如果你删除了这个约束,你会看到NHibernate插入了一个空的PostId的注释,然后用新的Post的Id更新它们。

你需要:


  1. 移除非空约束 调用

  2. 保留约束,映射关系的另一面(使之成为一个双向关系,并允许 Inverse 正确地工作)

这在一对多的NHibernate文档,最后请参阅非常重要的注意事项

>

I have Post and Comment classes, and they have a one to many relationship where Post has a list of Comments. How can I map this as a uni-directional relationship with Fluent NHibernate, since a comment does not need to know its parent Post? Currently, this is my mapping for Comment:

Id(x => x.Id);
Map(x => x.Body);
References(x => x.User);

and for Post:

Id(x => x.Id);
Map(x => x.Title);
HasMany(x => x.Comments)
    .Inverse()
    .WithKeyColumn("PostId")
    .Cascade.AllDeleteOrphan();

This doesnt work because when I try to save a Post instance with a newly added Comment, the foreign key on Comment (PostId) is left NULL. And of course a comment cannot be saved with a NULL PostId. I've tried removing the .Inverse() clause, but that doesn't work either.

解决方案

NHibernate doesn't support this mapping when you have a not-null constraint on your foreign key. If you remove that constraint, you'll see that NHibernate inserts the Comments with a null PostId, then updates them with the Id of the new Post.

You either need to:

  1. Remove the not-null constraint and the Inverse call
  2. Keep the constraint, and map the other side of the relationship (making this a bi-directional relationship, and allowing Inverse to work correctly)

This is covered in the NHibernate documentation for one-to-many's, see the Very Important Note at the end.

这篇关于流利的NHibernate一对多的单向映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆