2

Consider the following simplified domain:

public class Movie
{
    public virtual int Id { get; set; }
    public virtual MovieDetail MovieDetail { get; set; }
}

public class MovieDetail
{
    public virtual int Id { get; set; }
    public virtual Movie Movie { get; set; }
}

A MovieDetail cannot exist without a Movie, but a Movie could exist without a MovieDetail (i.e. we have no details about it).

Our database has a separate table for Movie with columns Id, and a separate table for MovieDetail with columns Id and MovieId. There is also a foreign key from MovieDetail.MovieId to Movie.Id.

We've got this all mapped in NHibernate, but when getting a collection of Movie instances, we want a left outer join with MovieDetail. If not, we could have a N+1 problem when iterating over the Movie instances. That is the case now: there is a separate query for every call to the Movie.MovieDetail property.

I've tried one-to-one mapping, but that seems to be for the case when you have both instances. In our case, we don't always have a MovieDetail. Also, they don't share the same primary key.

I've researched formula's, but that would require me to make my MovieDetail implement IUserType, essentially putting NHibernate into my domain. I'd like to avoid that.

4

2 回答 2

0

Movie也许您可以尝试在 to 的映射中添加多对一关系MovieDetail,它将充当一对一映射。

当您将选项“not-null”设置为“false”时,我想它也可以为空。我不知道你是否是延迟加载,当这是MovieDetail在需要时加载而不是通过左连接构造加载。

两个类中的所有属性不应该都是虚拟的吗?

<many-to-one name="MovieDetail" column="Id" class="MovieDetail" not-null="false" lazy="false"/>
于 2013-05-14T16:25:36.470 回答
0

我有点着急,我不知道您是否可以修改您的域/数据库架构,但您可能想尝试看看http://ayende.com/blog/3937/nhibernate-mapping -组件

在我看来,一个Movie最多可以有一个MovieDetail可能不存在的。MovieDetail可能具有 , , 等属性DescriptionReleaseDateActors真的不明白您为什么将这些概念分开。通过将它们组合在一起,您每次想要列出电影时加入的表格和 FK 将减少 1 个。

该组件允许您将数据隔离到一个单独的实体中,同时映射到与Movie.

于 2013-08-21T12:04:26.037 回答