一些背景知识。我们创建了一个名为SqlSum的类型。它有2个属性,Id和SumValue。
我在同一个会话中有两个查询:
SqlSum paidTemp = session.CreateSQLQuery(
"select count(p.id) as Id, Sum(p.PaymentAmount) as SumValue " +
"FROM StPayments p " +
"where p.Active = 1 and p.IsVoided = 0 and p.StCustomerFk = :custid")
.AddEntity(typeof(SqlSum))
.SetParameter("custid", cust.Id)
.List<SqlSum>().First();
if (paidTemp != null)
{
paid = paidTemp.SumValue;
}
SqlSum allocTemp = session.CreateSQLQuery(
"select count(pA.id) as Id, Sum(pA.Amount) As SumValue " +
"FROM StPaymentAllocations pA " +
"INNER JOIN StPayments p on pA.StPaymentFk = p.Id " +
"where pA.Active = 1 and p.StCustomerFk = :custid")
.AddEntity(typeof(SqlSum))
.SetParameter("custid", cust.Id)
.List<SqlSum>().First();
if (allocTemp != null)
{
allocated = allocTemp.SumValue;
}
我可以在分析器中清楚地看到paytemp的查询返回的是1575的和值,而allocTemp查询返回的值是1500,但是,付费和分配的变量都被赋值为1575.实际上,检查调试器中allocTemp.SumValue属性的值显示为1575。
现在,我进行了一些小的更改,并将每个查询都移到了自己的会话中:
using (var session = factory.OpenSession())
using (var trans = session.BeginTransaction(IsolationLevel.ReadCommitted))
{
SqlSum paidTemp = session.CreateSQLQuery(
"select count(p.id) as Id, Sum(p.PaymentAmount) as SumValue " +
"FROM StPayments p " +
"where p.Active = 1 and p.IsVoided = 0 and p.StCustomerFk = :custid")
.AddEntity(typeof(SqlSum))
.SetParameter("custid", cust.Id)
.List<SqlSum>().First();
if (paidTemp != null)
{
paid = paidTemp.SumValue;
}
trans.Commit();
session.Flush();
}
using (var session = factory.OpenSession())
using (var trans = session.BeginTransaction(IsolationLevel.ReadCommitted))
{
SqlSum allocTemp = session.CreateSQLQuery(
"select count(pA.id) as Id, Sum(pA.Amount) As SumValue " +
"FROM StPaymentAllocations pA " +
"INNER JOIN StPayments p on pA.StPaymentFk = p.Id " +
"where pA.Active = 1 and p.StCustomerFk = :custid")
.AddEntity(typeof(SqlSum))
.SetParameter("custid", cust.Id)
.List<SqlSum>().First();
if (allocTemp != null)
{
allocated = allocTemp.SumValue;
}
trans.Commit();
session.Flush();
}
执行此代码时,突然alloctemp.SumValue按预期为1500.
是什么导致第二个查询在第一个示例中保留第一个查询的值?
答案 0 :(得分:2)
如果您的Id
列值可以返回相同的值,那么第一级缓存已经认为此ID在其中,并且duplicate
行。
因此: -
Id
作为一列保留,请转换为dto
,记住要覆盖Equals
和GetHashCode
。例如see this exmple Id
(老实说我不确定这个名称)。