【问题标题】:Working around Duplicate association path bug in Nhibernate with Query Over使用 Query Over 解决 Nhibernate 中的重复关联路径错误
【发布时间】:2013-05-08 14:11:45
【问题描述】:

我有一些代码尝试访问相同的关联路径两次,它们实际上是相同的别名,但是因为我使用的是查询对象,所以我将它们放在两个不同的地方,我不确定如何获取别名。

可能是一些代码可以清除混乱:

var privateBlogQuery = new BlogQuery()
    .ByUser(1)
    .RemoveHidden()
    .FetchUserDetails();


//<-------- In Blog Query object class: ------>

/// Gets all the private blogs the user has permissions to view
public BlogQuery ByUser(int userId)
{
    var authorisedUsers = null;

    this.Left.JoinQueryOver(r => r.AuthorisedUsers, () => authorisedUsers)
        .Where(r => r.User.Id == userId);

    return this;
}

/// Removes all private blogs user has marked to be hidden
public BlogQuery RemoveHidden()
{
    var authorisedUsers = null;

    this.Left.JoinQueryOver(r => r.AuthorisedUsers, () => authorisedUsers)
        .Where(r => !r.IsHidden);

    return this;
}

/// Loads up details of all users who have permission 
/// to view the private blog
public BlogQuery FetchUserDetails()
{
    var users = null;
    var authorisedUsers = null;

    this.Left.JoinQueryOver(r => r.AuthorisedUsers, () => authorisedUsers)
        .Left.JoinQueryOver(r => r.User, () => users);

    return this;
}

有时我会单独使用所有 3 个条件,而生成的 sql 正是我所需要的,只要它们单独使用,一切都很好。

现在我需要一起使用它们,同时 nhibernate 抛出异常 duplicate alias 并且我更改了这三个函数的别名,但随后我收到了 duplicate association path 异常。

我在谷歌上搜索了一下learnt that it is a bug in hibernate,我还找到了一些workarounds on this bug

问题是我正在使用 Query 对象,因此 Query 结束了,我不确定如何在此处获取关联路径/别名。

请问我该怎么办?

【问题讨论】:

  • 这是一个非常具体的解决方法,可能不适用于您的情况,但是当我遇到它时,我能够通过将我的表映射到执行连接的模式绑定视图来解决这个问题我

标签: nhibernate fluent-nhibernate nhibernate-criteria queryover


【解决方案1】:
  • authorisedUsers 设为BlogQuery 的成员变量并使用标记/标志来了解ByUserRemoveHidden 是否应该加入
  • 使用JoinAlias

例子

AuthorisedUser authorisedUser;
bool authorisedUsersJoined;

public BlogQuery RemoveHidden()
{
    if (!authorisedUsersJoined)
        this.Left.JoinAlias(r => r.AuthorisedUsers, () => authorisedUser);

    this.Where(() => !authorisedUser.IsHidden);

    return this;
}

FetchUserDetails 与其他两个是互斥的,因为过滤关联会阻止 NH 初始化关联。您需要使用过滤器进行子查询并查询生成的 Id,然后进行初始化。

/// Loads up details of all users who have permission 
/// to view the private blog
public BlogQuery FetchUserDetails()
{

    this.Query = QueryOver.Of<Blog>()
        .WhereRestrictionOn(b => b.Id).IsIn(this.Query.Select(b => b.Id))
        .Fetch(r => r.AuthorisedUsers).Eager
            .ThenFetch(au => au.User).Eager;

    return this;
}

【讨论】:

  • 嗨 - 当authorisedUsersJoined 为真时,我将如何获取/设置.Where(() =&gt; !authorisedUser.IsHidden);?因为无论如何我都需要设置那个条件,所以我需要知道是否已经执行了连接..
  • 我修复了代码。无论条件如何,都应始终设置 where 条件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
相关资源
最近更新 更多