I have a database that shares columns for relationships. Here is the condensed table structure
Order
----------
OrderId int IDENTITY
OrderLine
----------
OrderId int NOT NULL
OrderLine int NOT NULL
OrderNote
----------
NoteId uniqueidentifier NOT NULL
OrderId int NOT NULL
OrderLineId int NULL
Basically the OrderNote table is shared between Order and OrderLine. If the OrderLineId column is null, the note belongs to the order. If the OrderLineId column is present, the note belongs to the order line. Here is what my classes look like:
class Order {
int OrderId {get; set;}
IList<OrderLine> Lines {get;}
IList<OrderNote> Notes {get;}
}
class OrderLine {
int OrderLineId {get; set;}
Order Order {get; set;}
IList<OrderNote> Notes {get;}
}
class OrderNote {
Order Order {get; set;}
OrderLine Line {get; set;}
Guid NoteId {get; set;}
}
If the OrderNote.Line is null, the note belongs only to the Order. If OrderNote.Line is not null, the note belongs to the order and the line. Here is what my mappings look like:
class OrderClassMap {
Id(x => x.OrderId).Generated.Identity();
HasMany(x => x.Lines).Inverse().KeyColumn("OrderId");
HasMany(x => x.Notes).Inverse().KeyColumn("OrderId");
}
class OrderLineClassMap {
CompositeId().KeyReference(x => x.Order, "OrderId").KeyProperty(x => x.OrderLineId);
HasMany(x => x.Notes).Inverse().KeyColumns.Add("OrderId", "OrderLineId");
}
class OrderNoteClassMap {
Id(x => x.NoteId).Generated.Assigned();
References(x => x.Order).Column("OrderId");
References(x => x.Line).Columns("OrderId", "OrderLineId");
}
When I try to save a new OrderNote, I get an error saying “Invalid index 11 for this SqlParameterCollection with Count=11. How do I correctly model and map this?
It seems you are talking about only 1 note per order and 1 note per orderline? If so, map the note as a column in order and also a note column for the orderline. The will make a big impact on performance having less joins and simple queries – (otherwise you need left outer joins and coalesce statements).
If you can have multiple notes per order and orderline then create seperate ordernote and orderlinenote value objects. Depends on the needs of having more that 1 note per order/orderline. Would lean towards 1 note per entity rather as this is the easiest and offers best performance and a ordernote and orderlinenote are different in terms of the domain design.
or