【问题标题】:NHibernate QueryOver and string.formatNHibernate QueryOver 和 string.format
【发布时间】:2014-07-02 06:48:55
【问题描述】:

我正在使用 NHibernate 中的 QueryOver,我想使用以下语法自定义我的投影 DTO 的一个属性:

IEnumerable<PersonResponseMessage> persons =
    session.QueryOver<PersonEntity>()
        .SelectList(list => list
            .Select(p => p.Active).WithAlias(() => dto.Active)
            .Select(p => p.Alert).WithAlias(() => dto.Alert)
            .Select(p => p.Comments).WithAlias(() => dto.Comments)
            .Select(p => string.Format("{0}api/Person/{1}", uriHelper.Root, p.Id)).WithAlias(() => dto.DetailsUrl)
        )
        .TransformUsing(Transformers.AliasToBean<PersonResponseMessage>())
        .List<PersonResponseMessage>();

不幸的是,NHibernate 无法做到这一点,并抛出异常:

未定义从范围“”引用的变量 P

【问题讨论】:

    标签: c# nhibernate queryover


    【解决方案1】:

    共有两种方式。部分我们可以在 DB 端移动该 concat 操作,如下所述:

    在这种情况下,我们将使用Projections.Concat

    .SelectList(list => list
        .Select(p => p.Active).WithAlias(() => dto.Active)
        .Select(p => p.Alert).WithAlias(() => dto.Alert)
        .Select(p => p.Comments).WithAlias(() => dto.Comments)
    
        // instead of this
        //.Select(p => string.Format("{0}api/Person/{1}", uriHelper.Root, p.Id))
        //       .WithAlias(() => dto.DetailsUrl)
    
        // use this
        .Select(p => Projections.Concat(uriHelper.Root, Projections.Concat, p.Id))
               .WithAlias(() => dto.DetailsUrl)
        )
        .TransformUsing(Transformers.AliasToBean<PersonResponseMessage>())
        .List<PersonResponseMessage>();
    

    但我会投票支持应用程序层的事后处理,在 C# 中:

    .SelectList(list => list
        .Select(p => p.Active).WithAlias(() => dto.Active)
        .Select(p => p.Alert).WithAlias(() => dto.Alert)
        .Select(p => p.Comments).WithAlias(() => dto.Comments)
    
        // just the ID
        .Select(p => p.Id).WithAlias(() => dto.Id)
        )
        .TransformUsing(Transformers.AliasToBean<PersonResponseMessage>())
        .List<PersonResponseMessage>()
        // do the concat here, once the data are transformed and in memory
        .Select(result => 
        {
            result.DetailsUrl = string.Format("{0}api/Person/{1}", uriHelper.Root, p.Id)
            return result;
        });
    

    【讨论】:

    • 完美运行,第二个选项我更喜欢,因为它适用于内存中已有的数据
    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多