Fluent NHibernate, working with interfaces

家住魔仙堡 提交于 2019-11-27 07:14:29

I find that there are valid reasons for using an interface instead of a concrete class as a property.

For example, if your Field class was in a seperate project to the Address class, and you didn't have a dependency on the Address class's project from the Field class's project.

There are other ways of dealing with this situation, but the simplest way is often to attempt what you are doing and explicity tell NHibernate the concrete class to use for IAddress.

You can now do this in Fluent NHibernate, like this:

References(x => x.Address, "AddressId")
    .Class(typeof(Address);

Unfortunately you can't do this with HasMany or HasManyToMany. I'm not sure if this would even be possible due to lack of good covariance support in C#.

On your Field object, you have an object of type IAddress. This could be implemented by any number of different implementations. With what you are asking, each implementation would have its own mapping, which would introduce any number of difficulties (impossibilities?) for NHibernate to handle.

A simple example would help to demonstrate. Say you have two IAddress implementations Address1, and Address2. They each are saved in their own table, tblAddress1, and tblAddress2. When you try to load your Field object, all NHibernate knows is that you have something that implements IAddress, it does not know which implementation was persisted. How would it know which mapping to use to retrieve the child object for any given field?

I'm sure there are more complications, but this example shows why you have to have a mapping for the exact type of object that you have declared.

Stumblor

If you are interested in decoupling your ORM entirely from your domain layer, and referencing interfaces throughout your data layer rather than specifying concrete classes, you can implement an EmptyInterceptor to map between the two.

See my answer here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!