views:

780

answers:

4

given the following class definition:

public class Order {
  public IProduct Product {get;set;}
}

I have this (fluent) mapping

References(x=>x.Product, "ProductId");

And get this exception: An association from the table Orders refers to an unmapped class, which makes sense because it doesn't know what implementation I will pass to it.

I understand why I have to define the type in the mapping (IProduct could be anything) but I'm not sure how to do it.

Thanks,

Kyle

+2  A: 

Try mapping the interface IProduct instead of the concrete class Product. (Note, I'm not talking about mapping the Product field of class Order.)

Justice
+1  A: 

You could map the interface->implementation relationship as an inheritance relationship, using an appropriate inheritance model.

That would mean mapping IProduct and then creating a subclass map of Product in the IProduct mapping, for example using table-per-hierarchy.

That would also let you map additional data in the product class that is not part of the IProduct interface, and also let you map additional IProduct implementations in the same way if you wish to.

Erik Öjebo
+1  A: 

I've been working on improving the support for proxy interfaces in Fluent. There were a couple of useful patches attached to issues 256 and 257, but they really needed everything specified manually. I've taken these a step further and added support for setting proxies and changing the types of references from the inferred (which would be the proxy) to the underlying mapped class, and added a new convention (ProxyConvention) to set it all up automatically - just instantiate it with a function to derive the proxy interface from a mapped class, and it should take care of the rest.

The one loophole at the moment is that it can't pick up any definitions specified explicitly in .hbm.xml files.

The patch is attached to issue 256

Dave Warry
+1  A: 

I think what you're looking for is .References<Question>(x=>x.Product, "ProductId");

Incidentally the same is true for .HasMany<>

This seems to do the same as <... class="Product" /> in xml

I wouldn't recommend mapping to the interface as it breaks the whole point of using one - you run into problems as soon as it starts implementing IStorable and NH can't cope with the multiple inheritance.

Stu
Thanks for this answer - I found it very helpful and was the approach I selected
Mike