QueryForObject方法当查询结果多于一条时,返回的是查询结果中的最后一条而不是第一条记录。
因为此方法以一般都针对只返回一条结果的查询,所以一直都没注意到,最近在解决一个Bug的时候才发现。
以下是Reflector查看IBatisNet.DataMapper.dll代码:
先从QueryForObject开始(命名空间IBasitNet.DataMapper.SqlMapper):
public T QueryForObject<T>(string statementName, object parameterObject)
{
...
local = this.GetMappedStatement(statementName).ExecuteQueryForObject<T>(localSession, parameterObject);
...
}
{
...
local = this.GetMappedStatement(statementName).ExecuteQueryForObject<T>(localSession, parameterObject);
...
}
转到ExecuteQueryForObject(命名空间:IBatisNet.DataMapper.MappedStatements.MappedStatement):
public virtual T ExecuteQueryForObject<T>(ISqlMapSession session, object parameterObject)
{
return this.ExecuteQueryForObject<T>(session, parameterObject, default(T));
}
public virtual T ExecuteQueryForObject<T>(ISqlMapSession session, object parameterObject, T resultObject)
{
...
return this.RunQueryForObject<T>(request, session, parameterObject, resultObject);
}
{
return this.ExecuteQueryForObject<T>(session, parameterObject, default(T));
}
public virtual T ExecuteQueryForObject<T>(ISqlMapSession session, object parameterObject, T resultObject)
{
...
return this.RunQueryForObject<T>(request, session, parameterObject, resultObject);
}
转到RunQueryForObject:
internal T RunQueryForObject<T>(RequestScope request, ISqlMapSession session, object parameterObject, T resultObject)
{
...
IDataReader reader = command.ExecuteReader();
...
while (reader.Read())
{
object obj2 = this._resultStrategy.Process(request, ref reader, resultObject);
if (obj2 != BaseStrategy.SKIP)
{
local = (T) obj2;
}
}
...
return local;
}
{
...
IDataReader reader = command.ExecuteReader();
...
while (reader.Read())
{
object obj2 = this._resultStrategy.Process(request, ref reader, resultObject);
if (obj2 != BaseStrategy.SKIP)
{
local = (T) obj2;
}
}
...
return local;
}
可以看到是遍历reader取值后返回。
注:本文使用DataMapper 1.6.1。