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?