ruskin
ruskin

Reputation: 479

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
{
  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?

Upvotes: 0

Views: 110

Answers (2)

Lester
Lester

Reputation: 4403

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

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

Upvotes: 1

VahidN
VahidN

Reputation: 19136

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.

Upvotes: 0

Related Questions