简体   繁体   中英

NHibernate Inheritance Mapping

I know in NHibernate you can have inheritance mappings, and I know you can have table-per-class, table-per-subclass and table-per-concrete-class but they don't quite fit the scenario I have.

Basically what I want is to be able to have a base class called product that looks like this:

public class BaseProduct 
{
     public virtual int ProductId {get;set;}
     public virtual string ProductName {get;set;}
}

which maps directly to a product table.

Then I want to have a Product class which inherits from BaseProduct like this:

public class Product : BaseProduct
{
    public virtual IList<Category> Categories {get;set;}
}

The thing is that the Product class should still map to the product table, the only difference being that this implementation has a list of Categories attached.

Without going into the technical reasons for why I need to do this, I would like to know if it's at all possible?

From your question and comment, I get that you want «Single Table Inheritance» [PoEAA, Fowler], but don't have the luxury of being able to add the needed discriminator to the table.

I've never run into this situation myself, but try to add a discriminator to your mapping which is a calculated value/derived field that uses sql to find out if there are foreign keys from Category (won't work for Products with empty Category collections though).

If your scenario is a read-only one, and you can add views to the DB, it's an option to map to a Product view with the discriminator calculated as stated above.

您正在寻找一个表类,您需要设置一个区分值NHDoc进行继承

Do you have other classes that inherit from BaseProduct? If not, you can just map the Product class only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM