NHibernate使用不正确的参数列表创建查询

时间:2017-07-26 14:02:27

标签: sql sql-server nhibernate fluent-nhibernate

我收到GenericADOException消息:

  

could not execute query

与以下查询相关,由NHibernate生成:

select aggregated0_.Id as col_0_0_
     , aggregated0_.Name as col_1_0_
     , aggregated0_.Event as col_2_0_
     , cast(count(distinct aggregated0_.Code) as INT) as col_3_0_ 
from Events aggregated0_ 
where 
    aggregated0_.RelatedId=@p0 
    and aggregated0_.S_Id=@p1
    and aggregated0_.HappenedAt >=@p2
group by 
    aggregated0_.Id
    , aggregated0_.Name
    , aggregated0_.Event    

Name:p1 - Value:97c58b27-460d-4fae-8185-b215e2d11882  
Name:p2 - Value:4d3b7583-4b46-46e2-8bcd-169b26fd3541  
Name:p3 - Value:7/25/2017 11:00:00 PM

如您所见,参数列表错误地使用了p1,p2和p3。但是,查询需要p0,p1和p2。

为什么NH会创建不正确的参数列表?

映射:

public AggregatedEventMap()
{
    SchemaAction.None();

    Table("Events");
    ReadOnly();
    Not.LazyLoad();

    Id(e => e.E_Id).GeneratedBy.Assigned();

    Map(m => m.RelatedId);
    Map(m => m.S_Id);
    Map(m => m.P_Id);
    Map(m => m.Id);
    Map(m => m.Name);
    Map(m => m.Code);
    Map(m => m.Event);

    Map(m => m.EventTime).CustomType<UtcDateTimeType>();
    Map(m => m.HappenedAt).CustomType<UtcDateTimeType>();
}

查询构建如下:

var query = 
    Session
        .Query<AggregatedEvent>()
        .Where(e => e.RelatedId == parameters.RelatedId);

        if (parameters.S_Id.HasValue)
        {
            query = 
                query.Where(e => e.S_Id == parameters.S_Id.Value);
        }

        if (parameters.P_Id.HasValue)
        {
            query = query.Where(e => e.P_Id == parameters.P_Id.Value);
        }

        if (parameters.Id.HasValue)
        {
            query = query.Where(e => e.Id == parameters.Id.Value);
        }

        if (parameters.FromDate.HasValue)
        {
            query = query.Where(e => e.HappenedAt >= parameters.FromDate.Value);
        }

        if (parameters.ToDate.HasValue)
        {
            query = query.Where(e => e.HappenedAt < parameters.ToDate.Value);
        }

var results =
    query
        .GroupBy(e => new { e.Id, e.Name, e.Event })
        .Select(
            g => 
                new AggregatedEventResult
                {
                    Id = g.Key.Id,
                    Name = g.Key.Name,
                    Event = g.Key.Event,
                    Count = g.Select(e => e.Code).Distinct().Count()
                })
                .ToList();

此外,这并不是一致发生的,只发生在一个运行时环境中。只有在使用某些参数组合时才会发生这种情况:

RelatedIdS_ID以及在指定日期之后或之后查询HappenedAt的时间。

0 个答案:

没有答案