开发者

One to many relationship not working in NHibernate

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
{
  p开发者_运维技巧ublic  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?


You need to add Cascade.SaveUpdate() to your automapping file. It should look something like:

HasMany(x => x.Books).Cascade.All();


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜