6

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?

accdias
  • 5,160
  • 3
  • 19
  • 31
stiank81
  • 25,418
  • 43
  • 131
  • 202

2 Answers2

8

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
  • 25,418
  • 43
  • 131
  • 202
2

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

Sly
  • 15,046
  • 12
  • 60
  • 89
  • 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 Jun 15 '10 at 08:56
  • 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 Jun 15 '10 at 09:00
  • http://stackoverflow.com/questions/1538248/fluent-nhibernate-mapping-a-class-with-subclass-problem/1538419#1538419 you can look here for an example – Sly Jun 15 '10 at 09:01