4
votes

I cannot figure out why NHibernate is inserting a child entity without the foreign key. Here are my classes

public class Order {
    public Order() {
        this.Notes = new List<OrderNote>();
    }

    public virtual int OrderId {get; private set;}
    public virtual IList<OrderNote> Notes {get; private set;}
}

public class OrderNote {
    public OrderNote(string noteBy, string note) {
        this.OrderNoteId = Guid.NewGuid();
        this.NoteBy = noteBy;
        this.Note = note;
    }

    public virtual Guid OrderNoteId {get; private set;}
    public virtual string NoteBy {get; private set;}
    public virtual string Note {get; private set;
}

Here are my Fluent NHibernate mapping files

public class OrderClassMap : ClassMap<Order> {
    public OrderClassMap() {
        Id(x => x.OrderId).GeneratedBy.Native();
        HasMany(x => x.Notes).Inverse.KeyColumn("OrderId").Cascase.AllDeleteOrphan();
    }
}

public class OrderNoteClassMap : ClassMap<OrderNote> {
    public OrderNoteClassMap() {
        Id(x => x.OrderNoteId).GeneratedBy.Assigned();
        Map(x => x.NoteBy);
        Map(x => x.Note);
    }
}

When I add a note to the order's notes collection and save the order, the order note gets inserted into the database without the foreign key.

Order order = session.Query<Order>().Where(o => (o.OrderId == orderId)).Single();
order.Notes.Add(new OrderNote("Name", "This is a note"));
session.SaveOrUpdate(order);

The insert statement that gets generated is this:

INSERT INTO OrderNotes(OrderNoteId, NoteBy, Note)

It should be:

INSERT INTO OrderNotes(OrderNoteId, NoteBy, Note, OrderId)

Why is this happening? What am I doing wrong?

2
I had this working before when the Order had a Guid as a RowId for its primary key. It still had a OrderId property and that was specified in the HasMany relationship as a PropertyRef.awilinsk

2 Answers

3
votes

Add an Order property to your OrderNote class and set that to the order object that you're adding the note to.

Also add a References(x => x.Order); to your OrderNoteClassMap

You can also try removing the Inverse on your HasMany mapping, but I don't think this will do it.

0
votes

Try create an inverse relation map from OrderNote to Order and add Order property in OrderNote class.

I use to create a method like "addNote"

Order order = session.Query<Order>().Where(o => (o.OrderId == orderId)).Single();
order.AddNote(new OrderNote("Name", "This is a note"));
session.SaveOrUpdate(order);

public virtual AddNote(OrderNote note)
{
note.Order=this;
order.Notes.Add(note);
}