源代码:Dapper/SqlMapper.cs at master · StackExchange/Dapper
Dapper QueryFirst核心演示using System.Data;
using System.Data.Common;
public static class DapperDemo
{
public static T QueryFirstOrDefault<T>(this IDbConnection connection,string sql,Func<IDataRecord,T> selector)
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
var data = (reader.Read() && reader.FieldCount != 0) ? selector(reader) : default(T);
while (reader.Read()) { }
while (reader.NextResult()) { }
return data;
}
}
}
}
为什么Dapper QueryFirst Core DataReader读到结尾而不是只读一次?
public static class DapperDemo
{
public static T QueryFirstOrDefault<T>(this IDbConnection connection,string sql,Func<IDataRecord,T> selector)
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
var data = (reader.Read() && reader.FieldCount != 0) ? selector(reader) : default(T); //Read only one time
return data;
}
}
}
}