Fluent NHibernate one to many uni-directional mapping

人走茶凉 提交于 2019-12-31 20:06:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/554674/fluent-nhibernate-one-to-many-uni-directional-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!