NHibernate DuplicateMappingException when mapping

2019-04-30 02:23发布

问题:

I have an abstract class, and subclasses of this, and I want to map this to my database using NHibernate. I'm using Fluent, and read on the wiki how to do the mapping. But when I add the mapping of the subclass an NHibernate.DuplicateMappingException is thrown when it is mapping. Why?

Here are my (simplified) classes:

public abstract class FieldValue
{
    public int Id { get; set; }
    public abstract object Value { get; set; }
}

public class StringFieldValue : FieldValue
{        
    public string ValueAsString { get; set; }
    public override object Value
    {
        get
        {
            return ValueAsString; 
        } 
        set
        {
            ValueAsString = (string)value; 
        }
    } 
}

And the mappings:

public class FieldValueMapping : ClassMap<FieldValue>
{
    public FieldValueMapping()
    {
        Id(m => m.Id).GeneratedBy.HiLo("1");
        // DiscriminateSubClassesOnColumn("type"); 
    }
}

public class StringValueMapping : SubclassMap<StringFieldValue>
{
    public StringValueMapping()
    { 
        Map(m => m.ValueAsString).Length(100);
    }
}

And the exception:

NHibernate.MappingException : Could not compile the mapping document: (XmlDocument) ----> NHibernate.DuplicateMappingException : Duplicate class/entity mapping NamespacePath.StringFieldValue

Any ideas?

回答1:

Discovered the problem. It turned out that I did reference the same Assembly several times in the PersistenceModel used to configure the database:

public class MappingsPersistenceModel : PersistenceModel
{
    public MappingsPersistenceModel()
    {
        AddMappingsFromAssembly(typeof(FooMapping).Assembly);
        AddMappingsFromAssembly(typeof(BarMapping).Assembly);
        // Where FooMapping and BarMapping is in the same Assembly. 
    }
}

Apparently this is not a problem for ClassMap-mappings. But for SubclassMap it doesn't handle it as well, causing duplicate mappings - and hence the DuplicateMappingException. Removing the duplicates in the PersistenceModel fixes the problem.



回答2:

If you are using automappings together with explicit mappings then fluent can generate two mappings for the same class.