How-to: Mapping (NHibernate) multiple classes with

2019-07-07 04:31发布

问题:

I am currently working with a brownfield database which contains a table which holds data for 3 different sorts of business. It has to do with SalesOrders and orderlines. In the old application, we were able to add 3 types of orderlines to each salesorder: products, hourly rates and text lines. 15 years ago, this was a quick and dirty solution to get easy queries in Delphi to get all the lines in one datagrid. Every

Now I am trying to build the object model in C# using NHibernate. I've made 3 seperate entities without a base class, due to the fact that these 3 line types have no real business logical connection. However, I want to get these 3 types into one list so I can order them.

I've considered using inheritence, table per class, as the table meets the requirements (no columns with a not-null restraint). This isn't a logical step though, since the business per type is completely different (only things in common are userId, description and remarks). Perhaps a component? but how to map the properties to 3 different classes without a base class or any kind of link except the table name?

I hope you guys understood what I wrote. I have no real code yet, I was just sketching some stuff on paper on how to deal with this code.

Anyone here who can help me on my way?

Kind regards, Ted

回答1:

You could put an interface on the three entities and map it as a base class, all to the same table:

interface IWhatever 
{
  // central Id for the whole table
  int Id { get; set; }
  // may be some more properties
}

class Product : IWhatever
{
  // ...
}

class HourlyRate : IWhatever
{
  // ...
}

class TextLines : IWhatever
{
  // ...
}

Mapping:

<class name="IWhatever" table="MyBigTable">

  <id .../>
  <discriminator column="Type"/>
  <subclass name="Product" discriminator-value="P">
    <!-- ... -->
  </subclass>
  <subclass name="HourlyRate" discriminator-value="HR">
    <!-- ... -->
  </subclass>
  <subclass name="TextLines" discriminator-value="TL">
    <!-- ... -->
  </subclass>
</class>