5

我想映射繼承鑑別器,但子類沒有鑑別器值。如何使用AutoMappings解決它?流利NHibernate自動映射與辨別器

域對象如下:

public abstract class Item : GuidIdentityEntity { 
    public virtual string Name { get; set; } 
} 

public class Product : Item {} 
public class RawMaterial : Item {} 

配置是這樣的:映射

AssemblyOf<Item>() 
    .IgnoreBase<GuidIdentityEntity>(); 
    .IncludeBase<Item>(); 
    .Setup(setup => { 
     setup.DiscriminatorColumn = type => "Discriminator"; 
     setup.IsDiscriminated = type => type == typeof(Item); 
     setup.SubclassStrategy = type => (type == typeof(Item)) 
      ? SubclassStrategy.Subclass 
      : SubclassStrategy.JoinedSubclass; 
    }); 

結果是:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true"> 
    <class xmlns="urn:nhibernate-mapping-2.2" name="Solution.Core.Products.Item, Solution.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2e5ef41be3839ad7" table="`Item`"> 
    <id name="Id" type="System.Guid, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> 
     <column name="Id" /> 
     <generator class="guid.comb" /> 
    </id> 
    <discriminator type="String"> 
     <column name="Discriminator" /> 
    </discriminator> 
    <property name="Name" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> 
     <column name="Name" /> 
    </property> 
    <subclass name="Solution.Core.Products.RawMaterial, Solution.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2e5ef41be3839ad7" /> 
    <subclass name="Solution.Core.Products.Product, Solution.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2e5ef41be3839ad7" /> 
    </class> 
</hibernate-mapping> 

回答

7

我發現這工作:

public class SubclassConvention : ISubclassConvention, ISubclassConventionAcceptance 
{ 
    #region IConvention<ISubclassInspector,ISubclassInstance> Members 

    public void Apply(ISubclassInstance instance) 
    { 
     if (instance.Name == typeof(SalesInvoice).AssemblyQualifiedName) 
      instance.DiscriminatorValue("SAL"); 
    } 

    #endregion 

    #region IConventionAcceptance<ISubclassInspector> Members 

    public void Accept(IAcceptanceCriteria<ISubclassInspector> criteria) 
    { 
     criteria.Expect(subclass => Type.GetType(subclass.Name).BaseType == typeof(Invoice)); 
    } 

    #endregion 
} 

在這種情況下,我有SalesInvoice類派生自Invoice類。當前子類從發票派生時,子類的接受標準爲true。鑑別器值是根據子類的類型分配的。如您所見,我使用名稱比較類型。不幸的是,由於某種原因,subclass.EntityType屬性在運行時爲null,所以我無法直接比較類型。