NHibernate mapping with a class hierarchy whose base class is abstract and the discriminator is not a string

大城市里の小女人 提交于 2019-12-04 11:39:07

问题


Here are the domain model classes:

public abstract class BaseClass
{
...
}

public class ChildClass : BaseClass
{
...
}

Note that the parent class is abstract and this is what gives me some difficulties when comes the time to map with fluent nhibernate. My discriminator is a byte (tinyint in the DB). Because it is not a string and I can't manage to set a discriminator value on the base class, this does not work (taken from the mapping class for BaseClass):

DiscriminateSubClassesOnColumn<byte>("Type")
    .SubClass<ChildClass>()
    .IsIdentifiedBy((byte)OperationType.Plan)
    .MapSubClassColumns(p => { ... })

The error message I get is:

Class Initialization method UnitTest1.MyClassInitialize threw exception. NHibernate.MappingException: NHibernate.MappingException: Could not format discriminator value to SQL string of entity BaseClass ---> System.FormatException: Input string was not in a correct format..

The following post seems to explain what happens. They give a solution with xml but not with fluent nhibernate: http://forum.hibernate.org/viewtopic.php?t=974225

Thanks for the help.


回答1:


I have found a workaround but this seems so like a patch... I added the following to the mapping file:

SetAttribute("discriminator-value", "-1");

It seems to instruct FNH not to use a string (I think it uses the class name) for the abstract base class. To make it work with the -1 value, I also changed my discriminator type from byte to sbyte.

Edit: I missed that: this is the second parameter to DiscriminateSubClassesOnColumn that takes the default value. So the correct answer to my question is:

DiscriminateSubClassesOnColumn<sbyte>("Type", (sbyte)-1)


来源:https://stackoverflow.com/questions/326174/nhibernate-mapping-with-a-class-hierarchy-whose-base-class-is-abstract-and-the-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!