Re: One-to-Many unidirectional association requires foreign key to be nullable

65 views
Skip to first unread message

cremor

unread,
Oct 2, 2012, 5:38:08 AM10/2/12
to nhu...@googlegroups.com
Just add not-null="true" to the key element of your collection mapping.

On Friday, September 21, 2012 11:40:11 AM UTC+2, Mouhong Lin wrote:
Hi guys,

This is the models:

public class BlogPost {
    public virtual int Id { get; set; }
    public virtual IList<Comment> Comments { get; set; }
}

public class Comment {
    public virtual int Id { get; set; }
    public virtual string Content { get; set; }

    // public virtual BlogPost BlogPost { get; set; }
}

Notice the commented line above. 

I do NOT want the bidirectional association between BlogPost and Comment. 
I want BlogPost to have a Comments collection, but do not want Comment to have a reference back to BlogPost.

As far as I know, this requires the mapping of Comments collection to be inverse = "false", and this requires the foreign key (BlogPostId) in the Comment table to be nullable. But from the database modeling's point of view, the foreign key BlogPostId should be not-null.

So, I want the foreign key BlogPostId in the Comment table to be not-null, while still keeping the association unidirectional, that is, remove the BlogPost property from Comment class. Can I do that? Thanks

BTW: Could anyone who is the manager of this group add me to the group? Now I can't publish posts without your verification. :-( Thanks.

cremor

unread,
Oct 9, 2012, 9:34:39 AM10/9/12
to nhu...@googlegroups.com
You use inverse="true" to tell NHibernate that the other side of the association is responsible for inserting and to ignore the elements in the collection. Of course in unidirectional associations you must not use inverse since there is no other side.

On Monday, October 8, 2012 9:42:20 AM UTC+2, Mouhong Lin wrote:
It works! Thanks! But what does "inverse" mean? So many articles say that inverse = false means the child objects should be inserted first, then the parent object. And then the foreign key in the child table gets updated. Like this one: http://blog.jonathanoliver.com/2009/09/nhibernate-inverse-and-object-associations/
If a not-null="true" can let parent object get inserted first, what is the use of the inverse attribute?
Reply all
Reply to author
Forward
0 new messages