开发者

Two way one-to-many association in NHibernate

开发者 https://www.devze.com 2023-04-05 01:56 出处:网络
With NHibernate, how do I make both user.AddPost(post) and post.setAuthor(user) behave the same way? Here are my classes:

With NHibernate, how do I make both user.AddPost(post) and post.setAuthor(user) behave the same way?

Here are my classes:

public class User
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual int Age { get; set; }

    private ICollection<Post> _posts = new HashSet<Post>();
    public virtual ICollection<Post> Posts
    {
        get { return _posts; }
        set { _posts = value; }
    }

    public override string ToString()
    {
        return string.Format("User{{id={0}, name='{1}', age={2}}}", Id, Name, Age);
    }开发者_StackOverflow中文版
}

public class Post
{
    public virtual int Id { get; set; }
    public virtual string Text { get; set; }
    public virtual User Author { get; set; }

    public override string ToString()
    {
        return string.Format("Post{{id={0}, text='{1}', author={2}}}", Id, Text, Author);
    }
}

Here are my mappings:

<class name="User" table="users">
  <id name="Id" type="int">
    <column name="Id" not-null="true" />
    <generator class="native"/>
  </id>
  <property name="Name" column="Name" />
  <property name="Age" column="Age" />
  <set name="Posts" inverse="true">
    <key column="AuthorId" />
    <one-to-many class="Post" />
  </set>
</class>

<class name="Post" table="posts">
  <id name="Id" type="int">
    <column name="Id" not-null="true" />
    <generator class="native"/>
  </id>
  <property name="Text" column="Text" />
  <many-to-one name="Author" column="AuthorId" class="User" />
</class>

The running code (works fine):

var user = new User {
  Name = "loki2302",
  Age = 100
};
session.Save(user);

var post = new Post {
  Text = "qwerty",
  Author = user
};
session.Save(post);

Is it possible to also enable this approach (doesn't work):

var user = new User {
  Name = "loki2302",
  Age = 100
};
session.Save(user);

var post = new Post {
  Text = "qwerty"
};
user.Posts.Add(post);
session.save(user);

?


I assume it fails because of a NOT NULL constraint on the author column? You don't set the Author property in the Post, so NHibernate inserts NULL in the foreign key column.

If you need a two-way relationship create a User.AddPost(Post) method where you add the post to the collection and set the Author property of it.

If you only need a collection in your code (but not the Author reference), just remove the Author property (and its mapping), remove the inverse="true" of you collection mapping and add not-null="true" to the key element of your collection mapping. That way the collection will handle the reference from Post to User.


As far as I understood you need to setup a cascading options for User entity.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号