views:

124

answers:

2

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?

+2  A: 

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

Sly
Yeah - I'm only using explicit mappings, but the thought crossed my mind.. I gotta have a look to see if it for some reason automatically mapped the subclass. Would it?
stiank81
This is the first time I use a SubclassMap. ClassMap's are not automapped, but could it be that SubclassMaps are? I don't have that much experience with Fluent..
stiank81
http://stackoverflow.com/questions/1538248/fluent-nhibernate-mapping-a-class-with-subclass-problem/1538419#1538419you can look here for an example
Sly
Checked more closely, and I am not using Automappings..
stiank81
+1  A: 

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.

stiank81