简体   繁体   English

NHibernate映射和Abstract类的继承

[英]Inheritance with NHibernate mapping and Abstract class

I am trying to map an class which two other classes will inherit from, i wish to make it abstract so i will be able to return a list which containing two type of child object and cast them accordingly with a discriminator in the parent class. 我试图映射一个将继承其他两个类的类,我希望将其抽象化,这样我将能够返回包含两种类型的子对象的列表,并在父类中使用区分符对它们进行相应的转换。

For an example of my codes, BD looks like the following: 对于我的代码示例,BD如下所示: 在此处输入图片说明

Here are my Domain models: 这是我的域模型:

public class Person
{
    public int id {get; set;}
    public string name{get; set;}
}

public class Teacher : Person
{
    public string subject{get; set;}
}

public class Student : Person
{
    public string grade{get; set;}
}

And my Nhibernate mapping: 而我的Nhibernate映射:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping namespace="Domain.Model" assembly="Domain" xmlns="urn:nhibernate-mapping-2.2" auto-import="false">
    <class name="Person" table="`Person`" schema="`PR`">
        <id name="id" access="property" column="`id`">
            <generator class="identity"/>
        </id>

        <property name="id" type="int" column="`id`" />
        <property name="name" type="String" column="`name`" />

        <joined-subclass name="Teacher" table="`Teacher`" schema="`PR`">
            <key column="`id`" />
            <property name="subject" type="String" column="`subject`" />
        </joined-subclass>
        <joined-subclass name="Student" table="`Student`" schema="`PR`">
            <key column="`id`" />
            <property name="grade" type="String" column="`grade`" />
        </joined-subclass>
    </class>
</hibernate-mapping>

I wish to make my "Person" class abstract so I will be able to have a list that can contain both child type but I'm not sure how to do it 我希望将“ Person”类抽象化,这样我就可以拥有一个可以包含两个子类型的列表,但是我不确定该怎么做

Polymorphism does not require the base class to be abstract. 多态不需要基类是抽象的。 You can work on a List<Person> containing Teacher and Student instances without having Person being abstract. 您可以在包含TeacherStudent实例的List<Person>上工作,而不必使Person是抽象的。

Setting Person as abstract in code only forbid to create a Person instance. 在代码中将Person设置为抽象仅禁止创建Person实例。

Setting Person as abstract in NHibernate mapping with a 'table per subclass' model tells to NHibernate that the Person table must have a corresponding entry in one of the subclass table. 在NHibernate映射中使用“每个子类的表”模型将Person设置为抽象,可以告诉NHibernate Person表必须在子类表之一中具有相应的条目。 If your DB contain some rows in Person without any corresponding row in Student or Teacher , then this is an error. 如果您的数据库包含某些行Person没有任何相应的行StudentTeacher ,那么这是一个错误。

Maybe this blog could help better understand what you should do. 也许此博客可以帮助您更好地了解您应该做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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