代码之家  ›  专栏  ›  技术社区  ›  Luke Smith

应用nhibernate筛选器时执行左外部联接

  •  1
  • Luke Smith  · 技术社区  · 15 年前

    我遇到的问题是,如果联接结果为空,筛选器将停止左外部联接的正常工作。

    作为一个很简单的例子,我想把所有的音乐家,如果他们在一个乐队,那么他们的乐队

    SELECT this_.Name, band2_.Name
    FROM   Musicians this_
           left outer join [Band] band2_
             on this_.BandID = band2_.ID
    WHERE  (band2_.IsDeleted = 0)
    

    如果音乐家不在乐队里,他们就不会回来了。我想要的是

    SELECT this_.Name, band2_.Name
    FROM   Musicians this_
           left outer join [Band] band2_
             on this_.BandID = band2_.ID
    WHERE  this_.ID = 4894 /* @p3 */
           (band2_.ID IS NULL OR band2_.IsDeleted = 0)
    

    有可能和nhibernate在一起吗?

    var projections = new[]
                    {
                        Projections.Property("Musician.Name").As("MusicianName"),
                        Projections.Property("Band.Name").As("BandName")
                    };
    
                return this.sessionProvider.GetSession().CreateCriteria<Musician>("Musician")
                    .CreateCriteria("Musician.Band", "Band", JoinType.LeftOuterJoin)
                    .SetProjection(projections)
                    .Add(Restrictions.Eq("Musician.ID", parameters.MusicianId))
                    .SetResultTransformer(Transformers.AliasToBean<MusicianDetailsResult>())
                    .UniqueResult<MusicianDetailsResult>();
    

    过滤器是用氟恩尼纤维酸盐定义的

    this.WithName(FilterName).WithCondition("IsDeleted = 0")
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   Jan Blaha    10 年前

    这是一个 bug in NHibernate .

    我用了建议的解决方法 useManyToOne ExposeConfiguration

    foreach (var key in cfg.FilterDefinitions.Keys)
    {
      filter = cfg.FilterDefinitions[key];
      cfg.FilterDefinitions[key] = new  FilterDefinition(
        filter.FilterName,
        filter.DefaultFilterCondition, 
        filter.ParameterTypes, false);
    }
    
        2
  •  0
  •   cbp    15 年前

    首先,如果你简单地将乐队映射到音乐家作为参考,这会容易得多:

    public class MusicianDbMap : ClassMap<Musician>
    {
        public MusicianDbMap()
        {
             ...
             References(x => x.Band)
                 .Nullable()
                 .Not.LazyLoad(); // Or lazy load... either way
        }
    }
    

     Session.Linq<Musician>()
          .Where(x => x.Band == null || !x.Band.IsDeleted)
          .ToList();
    

    其次,我不确定你的这句话:“如果音乐家不在乐队里,他们就不会回来了”。。。我不确定那是否正确。左外部联接应该返回所有行,不管它们是否在一个带中—您确定您没有在其他地方出错吗?