【问题标题】:Fluent NHibernate Mapping: one-to-one (or none)Fluent NHibernate 映射:一对一(或无)
【发布时间】:2014-09-01 13:12:28
【问题描述】:

我有一个无法真正更改的以下数据库方案设置。

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 对象访问时)始终为空。 我尝试了很多不同的方法来解决它,阅读了很多关于将其实现为一对多的内容。但是,我仍然无法让它工作。

任何帮助将不胜感激。

谢谢!

[Small UPDATE]:我只需要查询数据库,如果有任何相关性,则无需保存。

【问题讨论】:

  • HasOneReferences 设置对我有用。生成的 SQL NHibernate 对您来说是否正确?

标签: c# nhibernate fluent-nhibernate one-to-one fluent-nhibernate-mapping


【解决方案1】:

根据您的小幅更新,我将使用简化的映射。我们将受益于 NHibernate 真实映射能力,并优化用户加载。这一切都是因为我们确实需要只读映射。

首先,我们应该在Additional类中引入简单的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())

另见:

【讨论】:

    猜你喜欢
    • 2010-12-07
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2012-06-04
    相关资源
    最近更新 更多