一对多关系在 NHibernate 中不起作用
我正在使用 FluentHibernate 和 Automapping。我的课程
public class Student
{
public Student()
{
Books = new List<Book>();
}
public virtual int Id{get;private set;}
public virtual string Name{get;set;}
public virtual IList<Book> Books { get; private set; }
}
public class Book
{
public Book (){}
public virtual int Id{get;private set;}
public virtual string Name{get;set;}
}
Now, I create book objects and to a student object, and call save.
Book b = new Book();
b.Name = "test"
Book b1 = new Book();
b2.Name = "test1"
Student student = new Student();
student.Books.Add(b);
student.Books.Add(b1);
session.saveorupdate(student);
只有学生被保存,而不是书本。我做错了什么?
I am using FluentHibernate and Automapping. My classes are
public class Student
{
public Student()
{
Books = new List<Book>();
}
public virtual int Id{get;private set;}
public virtual string Name{get;set;}
public virtual IList<Book> Books { get; private set; }
}
public class Book
{
public Book (){}
public virtual int Id{get;private set;}
public virtual string Name{get;set;}
}
Now, I create book objects and to a student object, and call save.
Book b = new Book();
b.Name = "test"
Book b1 = new Book();
b2.Name = "test1"
Student student = new Student();
student.Books.Add(b);
student.Books.Add(b1);
session.saveorupdate(student);
Only student is saved not the books. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将 Cascade.SaveUpdate() 添加到自动映射文件中。它应该看起来像:
You need to add
Cascade.SaveUpdate()
to your automapping file. It should look something like:我认为这是多对多的关系,而不是一对多的关系(将更多的学生分配给一本独特的书目,反之亦然)。
所以你需要添加
public virtual IList;学生{得到;放; }
也到 Book 类。添加每本书后还可以调用 save 方法,以从数据库自动填充其 Id。
I thinks this is the many to many relationship not one to many (to assign more students to one unique book item and vice versa).
So you need to add
public virtual IList<Student> Students { get; set; }
to Book class as well.Also call save method after adding each book to populate its Id automatically from database.