I’m trying to learn NHibernate, and I’ve stumbled into a combined database design / “learning how NHibernate works” issue.
In my case, I’m trying to design a simple table with rows and columns, where each row has a “description” and then has a list of “column values” (of sorts), which contains the data as well as sorting information. In code, it’d look something like this:
public class Row
{
public virtual int ID { get; set; }
public virtual string Description { get; set; }
public virtual ICollection<Column> Columns { get; set; }
}
public class Column
{
public virtual Row ParentRow { get; set; }
public virtual int SortID { get; set; }
public virtual string Value { get; set; }
}
My ultimate goal was to create a database schema that would be…
- Two tables, “Row” and “Column”
- Row has two columns: ID and Description.
- Column has three columns: ParentID, SortID, and Value.
Because a column can only belong to one row, and ideally each column would have a unique sort ID within each ParentID, the primary key of the Column table could be ParentID and SortID, instead of having a fourth “ID” column.
However, NHibernate is fighting me at every turn. It insists that I must have an ID for the Column field. I suppose I have a few questions:
- Is my “schema goal” in and of itself that seriously flawed? Would it really be a better design for each Column to have its own ID? If so, why?
- Regardless of whether or not the schema I’m looking for is a good design, can this be accomplished in NHibernate? Thus far, I’ve successfully mapped the “Row” class, but I cannot map the “Column” class without NHibernate complaining that I have to provide it with an ID. (for what it’s worth, I’m using Fluent NHibernate). How do I circumvent that?
ORMs in general can map both Primary Keys and Composite Primary Key Identifiers. From those two options, you should choose what works best for your use case.
To learn how to map Composite Primary Key Identifiers, read composite-id section from the Nhibernate documentation.
All that said, from experience, I’ve found that non-composite primary key identifiers are your ORMs best friend. It makes life a lot easier in many cases, such as, application based id generation, batching etc. In tables similar to your “column” table I prefer to have a synthetic primary key identifier (Surrogate key). But again, it depends on your need, YMMV.