使用NHibernate,我該如何讓user.AddPost(post)
和post.setAuthor(user)
的行爲方式相同?NHibernate中的雙向一對多關聯
這裏是我的課:
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);
}
}
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);
}
}
這裏是我的映射:
<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>
運行的代碼(正常工作):
var user = new User {
Name = "loki2302",
Age = 100
};
session.Save(user);
var post = new Post {
Text = "qwerty",
Author = user
};
session.Save(post);
是否有可能也啓用此方法(不起作用):
var user = new User {
Name = "loki2302",
Age = 100
};
session.Save(user);
var post = new Post {
Text = "qwerty"
};
user.Posts.Add(post);
session.save(user);
?
您是否嘗試在創建用戶的同一個過程中創建一個帖子?如果它是實體,我會在用戶中創建一個帖子。新用戶{.. new Post {} ..} – Independent
@Jonas:嗯,我剛剛開始學習NHibernate,我有點困惑,雖然這兩種方法都很好,編譯和運行,只是有不同的結果。更具體地說,我要麼需要使兩種方法都能正常工作,要麼爲第二種方法(不工作),我希望至少得到運行時錯誤,所以我發現它並沒有達到我期望的效果去做。 – agibalov