【问题标题】:Filtering on a comparison of nullable strings过滤可空字符串的比较
【发布时间】:2011-10-18 04:25:19
【问题描述】:

我正在使用 nHibernate 来搜索不匹配的字符串。

型号是这样的:

  • PlayerGroup 有一个字段ExpectedPlaylistKey

  • Player 有一个字段LastReportedPlaylistKey

  • 一个PlayerGroup 有多个Players

我想执行查询以查找与该组的预期播放列表不匹配的所有玩家。

我的代码如下:

PlayerGroup playerGroupAlias = null;
Player playerAlias = null;

var query = this.Session.QueryOver<Player>(() => playerAlias)
                        .JoinAlias(() => playerAlias.PlayerGroup, () => playerGroupAlias)
                        .Where(
                                () => (playerGroupAlias.ExpectedPlaylistKey != playerAlias.CurrentlyReportedPlaylistKey)
                              );

我检查了生成的 SQL,它使用了这个 where 子句:

WHERE not (playergrou1_.ExpectedPlaylistKey = this_.CurrentlyReportedPlaylistKey)

不幸的是,如果其中一个值为 NULL,那么即使另一个值不为 null,也会返回 false。

如何修复我的 nHibernate 查询,以便在任一字符串为 NULL 时处理这种情况?

【问题讨论】:

    标签: nhibernate queryover


    【解决方案1】:

    我想出了一个可行的答案。

    但是,考虑到问题的简单性,这看起来是非常笨拙的代码。

    var query = this.Session.QueryOver<Player>(() => playerAlias)
        .JoinAlias(
            () => playerAlias.PlayerGroup,
            () => playerGroupAlias
        ).Where(
            () => 
                (
                    (playerAlias.CurrentlyReportedPlaylistKey == null) 
                        && (playerGroupAlias.ExpectedPlaylistKey != null)
                )
                || (
                    (playerAlias.CurrentlyReportedPlaylistKey != null) 
                        && (playerGroupAlias.ExpectedPlaylistKey == null)
                )
                || (
                   playerGroupAlias.ExpectedPlaylistKey != playerAlias.CurrentlyReportedPlaylistKey
                )
         );
    

    如您所见,我使用了一个包含五个比较以及五个其他布尔运算的 lambda 表达式,所有这些都是为了问“这两个字符串是否不同”这个问题? p>

    我希望有一个更优雅的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      相关资源
      最近更新 更多