Nhibernate linq n +1选择

时间:2014-09-14 13:58:03

标签: c# sql linq nhibernate fluent-nhibernate

这是我的课程:

public class Contract
{
    public virtual int Id { get; set; }
    public virtual IList<Stage> Stages { get; set; }
}

public class Stage
{
    public virtual int Id { get; set; }
    public virtual Contract Contract { get; set; }
    public decimal Cost { get; set; }
}

这是我的映射:

public class ContractMap: ClassMap<Contract>
{
    public ContractMap()
    {
        Id(x => x.Id);
        HasMany(x => x.Stages);
    }
}

public class StageMap: ClassMap<Stage>
{
    public StageMap()
    {
        Id(x => x.Id);
        Map(x => x.Cost);
        References(x => x.Contract);
    }
}

我想选择合约标识符及其各个阶段的总和。用linq看起来像这样:

session.Query<Contract>
    .Select(x => new { ContractId = x.Id, StagesCost = x.Stages.Sum(s => s.Cost) }).ToList();

不幸的是,这个linq表达式生成了这个sql:

select contract0_.Id as col_0_0_, 
(select cast(sum(stages2_.Cost) as DECIMAL(19,5)) from [Stage] stages2_ where contract0_.Id=stages2_.ContractId) as col_1_0_ 
from [Contract] contract0_

在这种情况下,Nhibernate使用带有n + 1选择问题的subselect。如何强制nhibernate使用join?

0 个答案:

没有答案