NHibernate - 不同会话之间的内部联接(不同的连接)

时间:2015-04-04 10:39:33

标签: c# sql-server linq nhibernate

我希望INNER JOIN语句写出两个不同的项目。

包括结果的第二个会话,但我无法获得

using (ISession session = Con1.OpenSessiongeneral())
{
    using (ISession session1 = Con2.OpenSessionsystem())
    {
        result = (from s in session.Query<AU_SalesTarget>()
              join t in session.Query<AU_Terms>() on s.termId equals t.termId
              join b in session1.Query<Branchs>() on s.branchId equals b.branchId
              select new SalesTarget_Derogate
              {
                  salesTargetId = s.salesTargetId,
                  mounth = t.month,
                  year = t.year,
                  calculateMethod = s.calculateMethod,
                  branchName = b.branchName
              }).Skip(0).Take(50).ToList<SalesTarget_Derogate>();
    }
}

list返回null

1 个答案:

答案 0 :(得分:0)

我不确定为什么你会得到一个空列表,但如果你的SQL Server实例支持不同实例之间的连接,你应该使用存储过程。

如果不支持,解决方案不优雅,您可以尝试先获取数据,然后使用linq加入它们:

using (ISession session = Con1.OpenSessiongeneral())
{
    result = (from s in session.Query<AU_SalesTarget>()
        join t in session.Query<AU_Terms>() on s.termId equals t.termId
            select new
            {
                 salesTargetId = s.salesTargetId,
                 mounth = t.month,
                 year = t.year,
                 calculateMethod = s.calculateMethod,
                 branchId = s.branchId
            })
        .Skip(0)
        .Take(50)
        .ToList();
}

var branchIds = result.Select(x => x.branchId)
    .List();
Branchs bAlias = null;
IList<Branchs> branches = null;

using (ISession session1 = Con2.OpenSessionsystem())
{
    branches = session1.QueryOver<Branchs>
        .WhereRestrictionOn(x => x.branchId).IsIn(branchIds)
        .Select(list => list
             .Select(x => x.branchId).WithAlias(() => bAlias.branchId)
             .Select(x => x.branchName).WithAlias(() => bAlias.branchName)
         )
         .TransformUsing(Transformers.AliasToBean<Branchs>())
        .List<Branchs>();
}

result = result.Join(branches, 
    x => x.branchId, 
    x => x.branchId, 
    (x, y) => new SalesTarget_Derogate
    {
        salesTargetId = x.salesTargetId,
        mounth = x.month,
        year = x.year,
        calculateMethod = x.calculateMethod,
        branchName = y.branchName
    }).ToList();