How do you map an entity -> interface relationship

2019-02-13 07:19发布

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

4条回答
ら.Afraid
2楼-- · 2019-02-13 07:32

I think what you're looking for is .References<Product>(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.

查看更多
Evening l夕情丶
3楼-- · 2019-02-13 07:36

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.

查看更多
4楼-- · 2019-02-13 07:38

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

查看更多
Melony?
5楼-- · 2019-02-13 07:52

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

查看更多
登录 后发表回答