public static IEnumerable <T> Query6 <T>(this IDbConnection cnn, string sql, object param = null) where T : new() { using (var command = cnn.CreateCommand()) { command.CommandText = sql; //dapper会在取缓存之前先正则匹配={变量名称}规格的替换 //Dapper Literal Replacements底层原理就是字串取代 CommandLiteralReplace(command, param); using (var reader = command.ExecuteReader()) { var identity = new DapperIdentity(command.CommandText, command.CommandType, cnn.ConnectionString, typeof(T), param?.GetType()); // 2. 如果cache有资料就使用,没有资料就动态建立方法并保存在缓存内 if (!readers.TryGetValue(identity, out Func <DbDataReader, object> func)) { //动态建立方法 func = GetTypeDeserializerImpl(typeof(T), reader); readers[identity] = func; Console.WriteLine("没有缓存,建立动态方法放进缓存"); } else { Console.WriteLine("使用缓存"); } // 3. 呼叫生成的方法by reader,读取资料回传 while (reader.Read()) { var result = func(reader as DbDataReader); yield return(result is T ? (T)result : default(T)); } } } }
public bool Equals(DapperIdentity other) { if (ReferenceEquals(this, other)) { return(true); } if (ReferenceEquals(other, null)) { return(false); } return(type == other.type && sql == other.sql && commandType == other.commandType && StringComparer.Ordinal.Equals(connectionString, other.connectionString) && parametersType == other.parametersType); }