How to map a list of an interface to a concrete class

Asbjørn Ulsberg's Avatar

Asbjørn Ulsberg

25 Oct, 2010 11:11 AM via web

I'd like to map a list of an interface This is my object:

public class Foo
{
  public virtual IList<IBar> Bars { get; protected set; }
}

I have several implementations of IBar in my domain model. How do I specify which IBar implementation Foo is using with Fluent NHibernate? I'm using auto mapping and would love if there was a solution with overrides.

I feel like there's a missing Class() method somewhere, but I don't know how to map this with NHibernate, so I'm not sure what I want to do is even possible.

  1. 2 Posted by Asbjørn Ulsberg on 25 Oct, 2010 12:22 PM

    Asbjørn Ulsberg's Avatar

    I can add that in the opposite direction of the many-to-one relationship, I have the following:

    public class Bar : IBar
    {
        public virtual IFoo Foo { get; protected set }
    }

    And I map this with the following override:

    public class BarMap : IAutoMappingOverride<Bar>
    {
        public void Override(AutoMapping<Bar> mapping)
        {
            mapping.References(x => x.Foo)
                   .Class<Foo>();
        }
    }
  2. 3 Posted by Asbjørn Ulsberg on 25 Oct, 2010 04:21 PM

    Asbjørn Ulsberg's Avatar

    In NHibernate, this seems to be the way to solve it:

    <class name="Foo">
        <bag name="Bars">
            <one-to-many class="Bar" />
        </bag>
    </class>

    However, I find no way to modify <one-to-many class="" /> with FNH, at least not with IAutoMappingOverride. Is there another way to access the @class attribute so I can set it to Bar instad of IBar?

  3. Support Staff 4 Posted by James Gregory on 26 Oct, 2010 12:20 PM

    James Gregory's Avatar

    Looks like that's not exposed through either the ClassMap API, or the IAutoMappingOverrides. That's a bummer.

    I think the only option you have (apart from using HBMs) is to create an IHasManyConvention and modify the Relationship property.

    public class BarsConvention : IHasManyConvention, IHasManyConventionAcceptance
    {
      public void Accept(IAcceptanceCriteria<IOneToManyCollectionInspector> criteria)
      {
        criteria.Expect(x => x.Relationship.Class == typeof(IBar));
      }
    
      public void Apply(IOneToManyCollectionInstance instance)
      {
        instance.Relationship.CustomClass<Bar>();
      }
    }

    That might not be perfect, as I don't have a compiler to hand, but it should be close enough.

Reply to this discussion

Preview Comments are parsed with Markdown. Help with syntax

Attached Files

    You can attach files up to 10MB

    What is fifteen divided by three?