views:

344

answers:

1

I've been trying for hours to get many-to-many relationship to save with Castle ActiveRecord. What am I doing wrong? I can't find anything in the documentation or on google. There is data in the database.

Courses have a many to many relationship with Books.

Test code.

Database.Course c = new Database.Course();
c.Number = "CS 433";
c.Name = "Databases";
c.Size = 34;
c.Books = Database.Book.FindAll();
c.Save();

Also doesn't work

foreach(Database.Book b in Database.Book.FindAll()){
    c.Books.Add(b);
}

Database Classes

[ActiveRecord]
public class Course : ActiveRecordValidationBase<Course>
{
    private int? id;
    private string number;
    private string name;
    private string description;
    private int size; //number of students in class

    //references
    private IList books = new ArrayList();


    public override string ToString()
    {
        return FormattedName;
    }

    public string FormattedName
    {
        get
        {
            return string.Format("{0} - {1}", Number, Name);
        }
    }

    [PrimaryKey]
    public int? Id
    {
        get { return id; }
        set { id = value; }
    }

    [Property, ValidateNonEmpty]
    public string Number
    {
        get { return number; }
        set { number = value; }
    }

    [Property, ValidateNonEmpty]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    [Property(ColumnType="StringClob")]
    public string Description
    {
        get { return description; }
        set { description = value; }
    }

    [Property]
    public int Size
    {
        get { return size; }
        set { size = value; }
    }

    [HasAndBelongsToMany(typeof(Book),
    Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id", Inverse = true)]
    public IList Books
    {
        get { return books; }
        set { books = value; }
    }
}

[ActiveRecord]
public class Book : ActiveRecordValidationBase<Book>
{
    private int? id;
    private string title;
    private string edition;
    private string isbn;
    private bool is_available_for_order;
    //relations
    private IList authors = new ArrayList();
    private IList bookordercount = new ArrayList();
    private IList courses = new ArrayList();
    private Inventory inventory;

    public override string ToString()
    {
        return FormattedName;
    }

    public string FormattedName
    {
        //*
        get {
            string str;
            if (Edition == null || Edition == "")
                str = Title;
            else
                str = string.Format("{0} ({1})", Title, Edition);

            if (Authors.Count != 0)
            {
                return string.Format("{0} by {1}", str, FormattedAuthors);
            }
            else
            {
                return str;
            }
        }
        /*/
        get
        {
            return Title;
        }
        //*/
    }

    public string FormattedAuthors
    {
        get
        {
            if (Authors.Count == 0) return "";

            StringBuilder sb = new StringBuilder();
            int i = 0, end = Authors.Count;
            foreach (Author a in Authors)
            {
                i++;
                sb.Append(a.FormattedName);
                if (i != end) sb.Append("; ");
            }
            return sb.ToString();
        }
    }


    [PrimaryKey]
    public int? Id
    {
        get { return id; }
        set { id = value; }
    }

    [Property, ValidateNonEmpty]
    public string Title
    {
        get { return title; }
        set { title = value; }
    }

    [Property]
    public string Edition
    {
        get { return edition; }
        set { edition = value; }
    }

    [Property, ValidateNonEmpty]
    public string Isbn
    {
        get { return isbn; }
        set { isbn = value; }
    }

    [Property]
    public bool IsAvailableForOrder
    {
        get { return is_available_for_order; }
        set { is_available_for_order = value; }
    }

    //relations

    [HasAndBelongsToMany(typeof(Author),
    Table = "BookAuthor", ColumnKey = "book_id", ColumnRef = "author_id")]
    public IList Authors
    {
        get { return authors; }
        set { authors = value; }
    }

    [HasMany(typeof(BookOrderCount), Table = "BookOrderCounts", ColumnKey = "BookId")]
    public IList BookOrderCount
    {
        get { return bookordercount; }
        set { bookordercount = value; }
    }

    [HasAndBelongsToMany(typeof(Course),
   Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id")]
    public IList Courses
    {
        get { return courses; }
        set { courses = value; }
    }

    [OneToOne]
    public Inventory Inventory
    {
        get { return inventory; }
        set { inventory = value; }
    }
}
+2  A: 

Make sure you put the Inverse = true where you want it. From the Castle AR docs,

It is wise to choose one side of the relation as the owner. The other side, the non-writable, need to use Inverse=true.

Put the Inverse = true on the other side of the relationship, like this:

[HasAndBelongsToMany(typeof(Book),
    Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id")]
    public IList<Book> Books

[HasAndBelongsToMany(typeof(Course),
   Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id", Inverse = true)]
    public IList<Course> Courses

You also have to add attributes to the top of both classes - at the moment they don't know what tables they're mapped to. Currently you have this:

public class Course : ActiveRecordBase<Course>

Add this (where "course" is the name of your Course table):

[ActiveRecord("course")]
public class Course : ActiveRecordBase<Course>
Gabriel Florit
Not sure what you mean. Course have `inverse = true` and Books does not. What are these "attributes" that you speak of?
epochwolf
Note my edits above. The Castle AR docs is a great resource, btw.
Gabriel Florit
@Gabriel: I'd use IList<T> instead of IList
Mauricio Scheffer
@mausch: True - didn't catch that, I was just copy/pasting the OP's code. Good eye.
Gabriel Florit
I have both of these my error is that it is trying to (re)save Book for some unknown reason.
rball