views:

128

answers:

1

I have an interesting issue today!! Basically I have two classes.

public class A : B
{
   public virtual new ISet<DifferentItem> Items {get;set;}
}

public class B
{
  public virtual int Id {get;set;}
  public virtual ISet<Item> Items {get;set;}
}

The subclass A hides the base class B property, Items and replaces it with a new property with the same name and a different type.

The mappings for these classes are

public class AMapping : SubclassMap<A>
{
  public AMapping()
  {
    HasMany(x=>x.Items)
      .LazyLoad()
      .AsSet();
  }
}

public class BMapping : ClassMap<B>
{
   public BMapping()
   {
     Id(x=>x.Id);

      HasMany(x=>x.Items)
        .LazyLoad()
        .AsSet();  
   }
}

However when I run my unit test to check the mapping I get the following exception:

Tests the A mapping: NHibernate.PropertyAccessException : Invalid Cast (check your mapping for property type mismatches); setter of A ----> System.InvalidCastException : Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericSet1[Item]' to type 'Iesi.Collections.Generic.ISet1[DifferentItem]'.

Anyone have any ideas?

Clearly it is something to do with the type of the collection on the sub-class. But I skimmed through the available options on the mapping class and nothing stood out as being the solution here.

A: 

Generics in c# does not support covariance, so essentially you can't have ISet<Item> and ISet<DifferentItem>. Since it's a limitation of the language you need to rethink your design. Or wait til c# 6.

ilivewithian