Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate DuplicateMappingException when mapping abstract class and subclass

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 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?

like image 570
stiank81 Avatar asked Jun 15 '10 08:06

stiank81


Video Answer


2 Answers

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.

like image 126
stiank81 Avatar answered Oct 12 '22 03:10

stiank81


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

like image 26
Sly Avatar answered Oct 12 '22 05:10

Sly