Fluent NHibernate映射:一对一(或无)

本文关键字:或无 一对一 NHibernate 映射 Fluent | 更新日期: 2023-09-27 18:20:17

我有下面的数据库方案设置,我真的无法更改。

User
----
Id    (primary key)
[Some simple properties...]

UserAdditionalData
------------------
Id     (primary key)
[Some simple properties...] 
USERID (foreign key to User)

很明显,User表实际上不记得它是否链接到UserAdditionalData记录,所以我认为我不能在这里称之为真正的一对一映射,因为它们也不共享互斥PK。

然而,在实践中,我希望能够处理User对象,例如,检查它是否有UserAdditionalData记录,如果有,则访问其属性。

我已经将我的BDO设置为:

public class User
{
    [Some simple properties...] 
    public virtual UserAdditionalData UserAdditionalData { get; set; }
}
public class UserAdditionalData
{
    [Some simple properties...] 
    public virtual User User { get; set; }  /* I have this here, 
                                               but I don't really ever 
                                               have to access it in this 
                                               direction */
}

我已经设置了这样的映射:

    public UserMapping()
    {
        Table("USER");
        [Some simple properties...] 
        HasOne(x => x.UserAdditionalData).Cascade.None();
    }

    public UserExtraMapping()
    {
        Table("USER_ADDITIONAL_DATA");
        [Some simple properties...] 
        References(x => x.User, "USERID").Unique();
    }

这一切都编译了,但我看到我的UserExtra对象(当通过User对象访问时)总是null。我尝试了很多不同的方法来实现这一点,读了很多关于将其作为一对多实现的文章。然而,我还是没能让它发挥作用。

任何帮助都将不胜感激。

谢谢!

[Small UPDATE]:我只需要查询数据库,如果以任何方式相关,则不保存到数据库。

Fluent NHibernate映射:一对一(或无)

基于您的小更新,我将使用简化的映射。我们将从NHibernate真正的映射能力中获利,并优化用户负载。所有这些都是因为我们确实需要只读映射。

首先,我们应该在附加类上引入简单的int属性UserId

// extra class is having an int property containig the foreign key
public class UserAdditionalData
{
    public virtual int UserId { get; set; }
}
// that would be the mapping:
public UserExtraMapping()
{
    ...
    Map(x => x.UserId, "USERID");
}

现在,我们将为延迟加载many-to-one使用优化的映射(即,与总是加载两端的一对一相比,只有在真正需要的情况下,我们才会获得参考数据!)

public UserMapping()
{
    ...
    References(x => x.UserAdditionalData)
          .LazyLoad()
          .PropertyRef(e => e.UserId)
          .Not.Insert()
          .Not.Update()
          ;
}

因此,对于只读,我最好使用many-to-one映射(References()

另请参阅:

  • 5.1.10.多对一
  • 按代码映射,ManyToOne(向下滚动到Fluent NHibernate的等效