Commit 071a3fd5 authored by Nick Craver's avatar Nick Craver

.editorconfig and formatting

parent 9e67f97f
# EditorConfig is awesome:http://EditorConfig.org
# top-most EditorConfig file
root = true
# Don't use tabs for indentation.
[*]
indent_style = space
# (Please don't specify an indent_size here; that has too many unintended consequences.)
# Code files
[*.{cs,csx,vb,vbx}]
indent_size = 4
insert_final_newline = true
charset = utf-8-bom
# Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2
# Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
# JSON files
[*.json]
indent_size = 2
# Dotnet code style settings:
[*.{cs,vb}]
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true
# Avoid "this." and "Me." if not necessary
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion
# Use language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
# Suggest more modern language features when available
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
# CSharp code style settings:
[*.cs]
# Prefer "var" everywhere
#csharp_style_var_for_built_in_types = true:suggestion
#csharp_style_var_when_type_is_apparent = false:suggestion
#csharp_style_var_elsewhere = true:suggestion
# Prefer method-like constructs to have a expression-body
csharp_style_expression_bodied_methods = true:none
csharp_style_expression_bodied_constructors = true:none
csharp_style_expression_bodied_operators = true:none
# Prefer property-like constructs to have an expression-body
csharp_style_expression_bodied_properties = true:none
csharp_style_expression_bodied_indexers = true:none
csharp_style_expression_bodied_accessors = true:none
# Suggest more modern language features when available
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion
# Newline settings
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
\ No newline at end of file
...@@ -92,7 +92,7 @@ public static partial class SqlMapperExtensions ...@@ -92,7 +92,7 @@ public static partial class SqlMapperExtensions
private static async Task<IEnumerable<T>> GetAllAsyncImpl<T>(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, string sql, Type type) where T : class private static async Task<IEnumerable<T>> GetAllAsyncImpl<T>(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, string sql, Type type) where T : class
{ {
var result = await connection.QueryAsync(sql); var result = await connection.QueryAsync(sql).ConfigureAwait(false);
var list = new List<T>(); var list = new List<T>();
foreach (IDictionary<string, object> res in result) foreach (IDictionary<string, object> res in result)
{ {
...@@ -313,7 +313,7 @@ public partial interface ISqlAdapter ...@@ -313,7 +313,7 @@ public partial interface ISqlAdapter
/// <param name="keyProperties">The key columns in this table.</param> /// <param name="keyProperties">The key columns in this table.</param>
/// <param name="entityToInsert">The entity to insert.</param> /// <param name="entityToInsert">The entity to insert.</param>
/// <returns>The Id of the row created.</returns> /// <returns>The Id of the row created.</returns>
Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert); Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, string tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert);
} }
public partial class SqlServerAdapter public partial class SqlServerAdapter
...@@ -330,10 +330,10 @@ public partial class SqlServerAdapter ...@@ -330,10 +330,10 @@ public partial class SqlServerAdapter
/// <param name="keyProperties">The key columns in this table.</param> /// <param name="keyProperties">The key columns in this table.</param>
/// <param name="entityToInsert">The entity to insert.</param> /// <param name="entityToInsert">The entity to insert.</param>
/// <returns>The Id of the row created.</returns> /// <returns>The Id of the row created.</returns>
public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert) public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, string tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert)
{ {
var cmd = $"INSERT INTO {tableName} ({columnList}) values ({parameterList}); SELECT SCOPE_IDENTITY() id"; var cmd = $"INSERT INTO {tableName} ({columnList}) values ({parameterList}); SELECT SCOPE_IDENTITY() id";
var multi = await connection.QueryMultipleAsync(cmd, entityToInsert, transaction, commandTimeout); var multi = await connection.QueryMultipleAsync(cmd, entityToInsert, transaction, commandTimeout).ConfigureAwait(false);
var first = multi.Read().FirstOrDefault(); var first = multi.Read().FirstOrDefault();
if (first == null || first.id == null) return 0; if (first == null || first.id == null) return 0;
...@@ -485,7 +485,7 @@ public partial class SQLiteAdapter ...@@ -485,7 +485,7 @@ public partial class SQLiteAdapter
public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, string tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert) public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, string tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert)
{ {
var cmd = $"INSERT INTO {tableName} ({columnList}) VALUES ({parameterList}); SELECT last_insert_rowid() id"; var cmd = $"INSERT INTO {tableName} ({columnList}) VALUES ({parameterList}); SELECT last_insert_rowid() id";
var multi = await connection.QueryMultipleAsync(cmd, entityToInsert, transaction, commandTimeout); var multi = await connection.QueryMultipleAsync(cmd, entityToInsert, transaction, commandTimeout).ConfigureAwait(false);
var id = (int)multi.Read().First().id; var id = (int)multi.Read().First().id;
var pi = keyProperties as PropertyInfo[] ?? keyProperties.ToArray(); var pi = keyProperties as PropertyInfo[] ?? keyProperties.ToArray();
...@@ -515,11 +515,11 @@ public partial class FbAdapter ...@@ -515,11 +515,11 @@ public partial class FbAdapter
public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, string tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert) public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, string tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert)
{ {
var cmd = $"insert into {tableName} ({columnList}) values ({parameterList})"; var cmd = $"insert into {tableName} ({columnList}) values ({parameterList})";
await connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout); await connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout).ConfigureAwait(false);
var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray(); var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray();
var keyName = propertyInfos[0].Name; var keyName = propertyInfos[0].Name;
var r = await connection.QueryAsync($"SELECT FIRST 1 {keyName} ID FROM {tableName} ORDER BY {keyName} DESC", transaction: transaction, commandTimeout: commandTimeout); var r = await connection.QueryAsync($"SELECT FIRST 1 {keyName} ID FROM {tableName} ORDER BY {keyName} DESC", transaction: transaction, commandTimeout: commandTimeout).ConfigureAwait(false);
var id = r.First().ID; var id = r.First().ID;
if (id == null) return 0; if (id == null) return 0;
......
...@@ -114,7 +114,7 @@ private static List<PropertyInfo> KeyPropertiesCache(Type type) ...@@ -114,7 +114,7 @@ private static List<PropertyInfo> KeyPropertiesCache(Type type)
if (keyProperties.Count == 0) if (keyProperties.Count == 0)
{ {
var idProp = allProperties.FirstOrDefault(p => p.Name.ToLower() == "id"); var idProp = allProperties.Find(p => string.Equals(p.Name, "id", StringComparison.CurrentCultureIgnoreCase));
if (idProp != null && !idProp.GetCustomAttributes(true).Any(a => a is ExplicitKeyAttribute)) if (idProp != null && !idProp.GetCustomAttributes(true).Any(a => a is ExplicitKeyAttribute))
{ {
keyProperties.Add(idProp); keyProperties.Add(idProp);
...@@ -148,7 +148,7 @@ private static bool IsWriteable(PropertyInfo pi) ...@@ -148,7 +148,7 @@ private static bool IsWriteable(PropertyInfo pi)
private static PropertyInfo GetSingleKey<T>(string method) private static PropertyInfo GetSingleKey<T>(string method)
{ {
var type = typeof (T); var type = typeof(T);
var keys = KeyPropertiesCache(type); var keys = KeyPropertiesCache(type);
var explicitKeys = ExplicitKeyPropertiesCache(type); var explicitKeys = ExplicitKeyPropertiesCache(type);
var keyCount = keys.Count + explicitKeys.Count; var keyCount = keys.Count + explicitKeys.Count;
...@@ -564,17 +564,17 @@ public static T GetInterfaceProxy<T>() ...@@ -564,17 +564,17 @@ public static T GetInterfaceProxy<T>()
private static MethodInfo CreateIsDirtyProperty(TypeBuilder typeBuilder) private static MethodInfo CreateIsDirtyProperty(TypeBuilder typeBuilder)
{ {
var propType = typeof(bool); var propType = typeof(bool);
var field = typeBuilder.DefineField("_" + "IsDirty", propType, FieldAttributes.Private); var field = typeBuilder.DefineField("_" + nameof(IProxy.IsDirty), propType, FieldAttributes.Private);
var property = typeBuilder.DefineProperty("IsDirty", var property = typeBuilder.DefineProperty(nameof(IProxy.IsDirty),
System.Reflection.PropertyAttributes.None, System.Reflection.PropertyAttributes.None,
propType, propType,
new[] { propType }); new[] { propType });
const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.NewSlot | MethodAttributes.SpecialName | const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.NewSlot | MethodAttributes.SpecialName
MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig; | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig;
// Define the "get" and "set" accessor methods // Define the "get" and "set" accessor methods
var currGetPropMthdBldr = typeBuilder.DefineMethod("get_" + "IsDirty", var currGetPropMthdBldr = typeBuilder.DefineMethod("get_" + nameof(IProxy.IsDirty),
getSetAttr, getSetAttr,
propType, propType,
Type.EmptyTypes); Type.EmptyTypes);
...@@ -582,7 +582,7 @@ private static MethodInfo CreateIsDirtyProperty(TypeBuilder typeBuilder) ...@@ -582,7 +582,7 @@ private static MethodInfo CreateIsDirtyProperty(TypeBuilder typeBuilder)
currGetIl.Emit(OpCodes.Ldarg_0); currGetIl.Emit(OpCodes.Ldarg_0);
currGetIl.Emit(OpCodes.Ldfld, field); currGetIl.Emit(OpCodes.Ldfld, field);
currGetIl.Emit(OpCodes.Ret); currGetIl.Emit(OpCodes.Ret);
var currSetPropMthdBldr = typeBuilder.DefineMethod("set_" + "IsDirty", var currSetPropMthdBldr = typeBuilder.DefineMethod("set_" + nameof(IProxy.IsDirty),
getSetAttr, getSetAttr,
null, null,
new[] { propType }); new[] { propType });
...@@ -594,8 +594,8 @@ private static MethodInfo CreateIsDirtyProperty(TypeBuilder typeBuilder) ...@@ -594,8 +594,8 @@ private static MethodInfo CreateIsDirtyProperty(TypeBuilder typeBuilder)
property.SetGetMethod(currGetPropMthdBldr); property.SetGetMethod(currGetPropMthdBldr);
property.SetSetMethod(currSetPropMthdBldr); property.SetSetMethod(currSetPropMthdBldr);
var getMethod = typeof(IProxy).GetMethod("get_" + "IsDirty"); var getMethod = typeof(IProxy).GetMethod("get_" + nameof(IProxy.IsDirty));
var setMethod = typeof(IProxy).GetMethod("set_" + "IsDirty"); var setMethod = typeof(IProxy).GetMethod("set_" + nameof(IProxy.IsDirty));
typeBuilder.DefineMethodOverride(currGetPropMthdBldr, getMethod); typeBuilder.DefineMethodOverride(currGetPropMthdBldr, getMethod);
typeBuilder.DefineMethodOverride(currSetPropMthdBldr, setMethod); typeBuilder.DefineMethodOverride(currSetPropMthdBldr, setMethod);
...@@ -841,7 +841,7 @@ public int Insert(IDbConnection connection, IDbTransaction transaction, int? com ...@@ -841,7 +841,7 @@ public int Insert(IDbConnection connection, IDbTransaction transaction, int? com
var r = connection.Query("select @@IDENTITY id", transaction: transaction, commandTimeout: commandTimeout).ToList(); var r = connection.Query("select @@IDENTITY id", transaction: transaction, commandTimeout: commandTimeout).ToList();
if (r[0].id == null) return 0; if (r[0].id == null) return 0;
var id = (int) r[0].id; var id = (int)r[0].id;
var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray(); var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray();
if (propertyInfos.Length == 0) return id; if (propertyInfos.Length == 0) return id;
...@@ -1112,4 +1112,4 @@ public void AppendColumnNameEqualsValue(StringBuilder sb, string columnName) ...@@ -1112,4 +1112,4 @@ public void AppendColumnNameEqualsValue(StringBuilder sb, string columnName)
{ {
sb.AppendFormat("{0} = @{1}", columnName, columnName); sb.AppendFormat("{0} = @{1}", columnName, columnName);
} }
} }
\ No newline at end of file
...@@ -88,7 +88,7 @@ public Task<int> UpdateAsync(TId id, dynamic data) ...@@ -88,7 +88,7 @@ public Task<int> UpdateAsync(TId id, dynamic data)
/// <param name="param">The parameters to use.</param> /// <param name="param">The parameters to use.</param>
/// <returns>The number of rows affected.</returns> /// <returns>The number of rows affected.</returns>
public Task<int> ExecuteAsync(string sql, dynamic param = null) => public Task<int> ExecuteAsync(string sql, dynamic param = null) =>
_connection.ExecuteAsync(sql, param as object, _transaction, this._commandTimeout); _connection.ExecuteAsync(sql, param as object, _transaction, _commandTimeout);
/// <summary> /// <summary>
/// Asynchronously queries the current database. /// Asynchronously queries the current database.
......
...@@ -166,10 +166,10 @@ public class Table<T> : Table<T, int> ...@@ -166,10 +166,10 @@ public class Table<T> : Table<T, int>
/// <param name="database">The database this table belongs in.</param> /// <param name="database">The database this table belongs in.</param>
/// <param name="likelyTableName">The name for this table.</param> /// <param name="likelyTableName">The name for this table.</param>
public Table(Database<TDatabase> database, string likelyTableName) public Table(Database<TDatabase> database, string likelyTableName)
: base(database, likelyTableName) : base(database, likelyTableName)
{ {
} }
} }
private DbConnection _connection; private DbConnection _connection;
private int _commandTimeout; private int _commandTimeout;
...@@ -238,7 +238,7 @@ public void RollbackTransaction() ...@@ -238,7 +238,7 @@ public void RollbackTransaction()
/// <returns>The function to create the <paramref name="tableType"/> table.</returns> /// <returns>The function to create the <paramref name="tableType"/> table.</returns>
protected Action<TDatabase> CreateTableConstructor(Type tableType) protected Action<TDatabase> CreateTableConstructor(Type tableType)
{ {
return CreateTableConstructor(new[] {tableType}); return CreateTableConstructor(new[] { tableType });
} }
/// <summary> /// <summary>
...@@ -315,7 +315,7 @@ private bool TableExists(string name) ...@@ -315,7 +315,7 @@ private bool TableExists(string name)
name = name.Replace("[", ""); name = name.Replace("[", "");
name = name.Replace("]", ""); name = name.Replace("]", "");
if(name.Contains(".")) if (name.Contains("."))
{ {
var parts = name.Split('.'); var parts = name.Split('.');
if (parts.Length == 2) if (parts.Length == 2)
......
This diff is collapsed.
...@@ -40,7 +40,7 @@ public async Task InsertGetUpdateDeleteWithExplicitKeyAsync() ...@@ -40,7 +40,7 @@ public async Task InsertGetUpdateDeleteWithExplicitKeyAsync()
var originalyCount = connection.Query<int>("Select Count(*) From ObjectY").First(); var originalyCount = connection.Query<int>("Select Count(*) From ObjectY").First();
await connection.InsertAsync(o2).ConfigureAwait(false); await connection.InsertAsync(o2).ConfigureAwait(false);
var list2 = (await connection.QueryAsync<ObjectY>("select * from ObjectY").ConfigureAwait(false)).ToList(); var list2 = (await connection.QueryAsync<ObjectY>("select * from ObjectY").ConfigureAwait(false)).ToList();
Assert.Equal(list2.Count, originalyCount+1); Assert.Equal(list2.Count, originalyCount + 1);
o2 = await connection.GetAsync<ObjectY>(id).ConfigureAwait(false); o2 = await connection.GetAsync<ObjectY>(id).ConfigureAwait(false);
Assert.Equal(o2.ObjectYId, id); Assert.Equal(o2.ObjectYId, id);
o2.Name = "Bar"; o2.Name = "Bar";
...@@ -112,13 +112,13 @@ public async Task InsertGetUpdateAsync() ...@@ -112,13 +112,13 @@ public async Task InsertGetUpdateAsync()
Assert.True(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false)); Assert.True(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false));
Assert.Equal("Cecil", (await connection.GetAsync<User>(id).ConfigureAwait(false)).Name); Assert.Equal("Cecil", (await connection.GetAsync<User>(id).ConfigureAwait(false)).Name);
Assert.Equal((await connection.QueryAsync<User>("select * from Users").ConfigureAwait(false)).Count(), originalCount+1); Assert.Equal((await connection.QueryAsync<User>("select * from Users").ConfigureAwait(false)).Count(), originalCount + 1);
Assert.True(await connection.DeleteAsync(user).ConfigureAwait(false)); Assert.True(await connection.DeleteAsync(user).ConfigureAwait(false));
Assert.Equal((await connection.QueryAsync<User>("select * from Users").ConfigureAwait(false)).Count(), originalCount); Assert.Equal((await connection.QueryAsync<User>("select * from Users").ConfigureAwait(false)).Count(), originalCount);
Assert.False(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false)); //returns false, user not found Assert.False(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false)); //returns false, user not found
Assert.True(await connection.InsertAsync(new User {Name = "Adam", Age = 10}).ConfigureAwait(false) > originalCount + 1); Assert.True(await connection.InsertAsync(new User { Name = "Adam", Age = 10 }).ConfigureAwait(false) > originalCount + 1);
} }
} }
...@@ -348,4 +348,4 @@ public async Task DeleteAllAsync() ...@@ -348,4 +348,4 @@ public async Task DeleteAllAsync()
} }
} }
} }
} }
\ No newline at end of file
...@@ -180,7 +180,7 @@ public void GetAllWithExplicitKey() ...@@ -180,7 +180,7 @@ public void GetAllWithExplicitKey()
var objectXs = connection.GetAll<ObjectX>().ToList(); var objectXs = connection.GetAll<ObjectX>().ToList();
Assert.True(objectXs.Count > 0); Assert.True(objectXs.Count > 0);
Assert.Equal(1, objectXs.Count(x => x.ObjectXId== guid)); Assert.Equal(1, objectXs.Count(x => x.ObjectXId == guid));
} }
} }
......
...@@ -63,7 +63,7 @@ public class MySqlServerTestSuite : TestSuite ...@@ -63,7 +63,7 @@ public class MySqlServerTestSuite : TestSuite
{ {
private const string DbName = "DapperContribTests"; private const string DbName = "DapperContribTests";
public static string ConnectionString { get; private set; } = public static string ConnectionString { get; } =
IsAppVeyor IsAppVeyor
? "Server=localhost;Uid=root;Pwd=Password12!;" ? "Server=localhost;Uid=root;Pwd=Password12!;"
: "Server=localhost;Uid=test;Pwd=pass;"; : "Server=localhost;Uid=test;Pwd=pass;";
......
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes;
using Dapper.Contrib.Extensions; using Dapper.Contrib.Extensions;
using System.Linq; using System.Linq;
...@@ -50,7 +50,7 @@ public dynamic QueryFirstOrDefaultDynamic() ...@@ -50,7 +50,7 @@ public dynamic QueryFirstOrDefaultDynamic()
Step(); Step();
return _connection.QueryFirstOrDefault("select * from Posts where Id = @Id", new { Id = i }).First(); return _connection.QueryFirstOrDefault("select * from Posts where Id = @Id", new { Id = i }).First();
} }
[Benchmark(Description = "Contrib Get<T>")] [Benchmark(Description = "Contrib Get<T>")]
public Post ContribGet() public Post ContribGet()
{ {
...@@ -58,4 +58,4 @@ public Post ContribGet() ...@@ -58,4 +58,4 @@ public Post ContribGet()
return _connection.Get<Post>(i); return _connection.Get<Post>(i);
} }
} }
} }
\ No newline at end of file
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes;
using System; using System;
using System.Data; using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
...@@ -86,8 +86,8 @@ public dynamic DataTableDynamic() ...@@ -86,8 +86,8 @@ public dynamic DataTableDynamic()
reader.Read(); reader.Read();
reader.GetValues(values); reader.GetValues(values);
_table.Rows.Add(values); _table.Rows.Add(values);
return _table.Rows[_table.Rows.Count-1]; return _table.Rows[_table.Rows.Count - 1];
} }
} }
} }
} }
\ No newline at end of file
...@@ -9,6 +9,6 @@ public EFContext(DbConnection connection, bool owned = false) : base(connection, ...@@ -9,6 +9,6 @@ public EFContext(DbConnection connection, bool owned = false) : base(connection,
{ {
} }
public DbSet<Post> Posts { get;set; } public DbSet<Post> Posts { get; set; }
} }
} }
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Data.Linq; using System.Data.Linq;
...@@ -145,7 +145,7 @@ public async Task RunAsync(int iterations) ...@@ -145,7 +145,7 @@ public async Task RunAsync(int iterations)
var entityContext2 = new EFContext(connection); var entityContext2 = new EFContext(connection);
tests.Add(id => entityContext2.Database.SqlQuery<Post>("select * from Posts where Id = {0}", id).First(), "Entity Framework: SqlQuery"); tests.Add(id => entityContext2.Database.SqlQuery<Post>("select * from Posts where Id = {0}", id).First(), "Entity Framework: SqlQuery");
var entityContext3 = new EFContext(connection); var entityContext3 = new EFContext(connection);
tests.Add(id => entityContext3.Posts.AsNoTracking().First(p => p.Id == id), "Entity Framework: No Tracking"); tests.Add(id => entityContext3.Posts.AsNoTracking().First(p => p.Id == id), "Entity Framework: No Tracking");
}, "Entity Framework"); }, "Entity Framework");
...@@ -266,7 +266,8 @@ public async Task RunAsync(int iterations) ...@@ -266,7 +266,8 @@ public async Task RunAsync(int iterations)
}, "Belgrade Sql Client"); }, "Belgrade Sql Client");
//Susanoo //Susanoo
Try(() => { Try(() =>
{
var susanooDb = new DatabaseManager(connection); var susanooDb = new DatabaseManager(connection);
var susanooPreDefinedCommand = var susanooPreDefinedCommand =
...@@ -307,7 +308,8 @@ public async Task RunAsync(int iterations) ...@@ -307,7 +308,8 @@ public async Task RunAsync(int iterations)
}, "ServiceStack.OrmLite"); }, "ServiceStack.OrmLite");
// Hand Coded // Hand Coded
Try(() => { Try(() =>
{
var postCommand = new SqlCommand() var postCommand = new SqlCommand()
{ {
Connection = connection, Connection = connection,
...@@ -398,4 +400,4 @@ public async Task RunAsync(int iterations) ...@@ -398,4 +400,4 @@ public async Task RunAsync(int iterations)
} }
} }
} }
} }
\ No newline at end of file
...@@ -25,7 +25,7 @@ public async Task TestBasicStringUsageAsync() ...@@ -25,7 +25,7 @@ public async Task TestBasicStringUsageAsync()
[Fact] [Fact]
public async Task TestBasicStringUsageQueryFirstAsync() public async Task TestBasicStringUsageQueryFirstAsync()
{ {
var str = await connection.QueryFirstAsync<string>(new CommandDefinition("select 'abc' as [Value] union all select @txt", new {txt = "def"})).ConfigureAwait(false); var str = await connection.QueryFirstAsync<string>(new CommandDefinition("select 'abc' as [Value] union all select @txt", new { txt = "def" })).ConfigureAwait(false);
Assert.Equal("abc", str); Assert.Equal("abc", str);
} }
...@@ -39,7 +39,7 @@ public async Task TestBasicStringUsageQueryFirstAsyncDynamic() ...@@ -39,7 +39,7 @@ public async Task TestBasicStringUsageQueryFirstAsyncDynamic()
[Fact] [Fact]
public async Task TestBasicStringUsageQueryFirstOrDefaultAsync() public async Task TestBasicStringUsageQueryFirstOrDefaultAsync()
{ {
var str = await connection.QueryFirstOrDefaultAsync<string>(new CommandDefinition("select null as [Value] union all select @txt", new {txt = "def"})).ConfigureAwait(false); var str = await connection.QueryFirstOrDefaultAsync<string>(new CommandDefinition("select null as [Value] union all select @txt", new { txt = "def" })).ConfigureAwait(false);
Assert.Null(str); Assert.Null(str);
} }
...@@ -165,7 +165,8 @@ public async Task TestMultiMapWithSplitAsync() ...@@ -165,7 +165,8 @@ public async Task TestMultiMapWithSplitAsync()
public async Task TestMultiMapArbitraryWithSplitAsync() public async Task TestMultiMapArbitraryWithSplitAsync()
{ {
const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name"; const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name";
var productQuery = await connection.QueryAsync<Product>(sql, new[] { typeof(Product), typeof(Category) }, (objects) => { var productQuery = await connection.QueryAsync<Product>(sql, new[] { typeof(Product), typeof(Category) }, (objects) =>
{
var prod = (Product)objects[0]; var prod = (Product)objects[0];
prod.Category = (Category)objects[1]; prod.Category = (Category)objects[1];
return prod; return prod;
...@@ -393,7 +394,8 @@ public void AssertNoCacheWorksForQueryMultiple() ...@@ -393,7 +394,8 @@ public void AssertNoCacheWorksForQueryMultiple()
const int a = 123, b = 456; const int a = 123, b = 456;
var cmdDef = new CommandDefinition("select @a; select @b;", new var cmdDef = new CommandDefinition("select @a; select @b;", new
{ {
a, b a,
b
}, commandType: CommandType.Text, flags: CommandFlags.NoCache); }, commandType: CommandType.Text, flags: CommandFlags.NoCache);
int c, d; int c, d;
...@@ -784,7 +786,7 @@ public async Task Issue157_ClosedReaderAsync() ...@@ -784,7 +786,7 @@ public async Task Issue157_ClosedReaderAsync()
var args = new { x = 42 }; var args = new { x = 42 };
const string sql = "select 123 as [A], 'abc' as [B] where @x=42"; const string sql = "select 123 as [A], 'abc' as [B] where @x=42";
var row = (await connection.QueryAsync<SomeType>(new CommandDefinition( var row = (await connection.QueryAsync<SomeType>(new CommandDefinition(
sql, args, flags:CommandFlags.None)).ConfigureAwait(false)).Single(); sql, args, flags: CommandFlags.None)).ConfigureAwait(false)).Single();
Assert.NotNull(row); Assert.NotNull(row);
Assert.Equal(123, row.A); Assert.Equal(123, row.A);
Assert.Equal("abc", row.B); Assert.Equal("abc", row.B);
...@@ -828,4 +830,4 @@ public async Task Issue563_QueryAsyncShouldThrowException() ...@@ -828,4 +830,4 @@ public async Task Issue563_QueryAsyncShouldThrowException()
catch (SqlException ex) when (ex.Message == "after select") { /* swallow only this */ } catch (SqlException ex) when (ex.Message == "after select") { /* swallow only this */ }
} }
} }
} }
\ No newline at end of file
...@@ -91,9 +91,9 @@ union all ...@@ -91,9 +91,9 @@ union all
var col = reader.GetOrdinal("Type"); var col = reader.GetOrdinal("Type");
var splitOn = reader.GetOrdinal("Id"); var splitOn = reader.GetOrdinal("Id");
var toFoo = reader.GetRowParser<DiscriminatedWithMultiMapping_BaseType>(typeof(DiscriminatedWithMultiMapping_Foo),0, splitOn); var toFoo = reader.GetRowParser<DiscriminatedWithMultiMapping_BaseType>(typeof(DiscriminatedWithMultiMapping_Foo), 0, splitOn);
var toBar = reader.GetRowParser<DiscriminatedWithMultiMapping_BaseType>(typeof(DiscriminatedWithMultiMapping_Bar),0, splitOn); var toBar = reader.GetRowParser<DiscriminatedWithMultiMapping_BaseType>(typeof(DiscriminatedWithMultiMapping_Bar), 0, splitOn);
var toHaz = reader.GetRowParser<HazNameId>(typeof(HazNameId),splitOn, reader.FieldCount - splitOn); var toHaz = reader.GetRowParser<HazNameId>(typeof(HazNameId), splitOn, reader.FieldCount - splitOn);
do do
{ {
...@@ -102,10 +102,10 @@ union all ...@@ -102,10 +102,10 @@ union all
{ {
case 1: case 1:
obj = toFoo(reader); obj = toFoo(reader);
break; break;
case 2: case 2:
obj = toBar(reader); obj = toBar(reader);
break; break;
} }
Assert.NotNull(obj); Assert.NotNull(obj);
...@@ -165,4 +165,4 @@ private class DiscriminatedWithMultiMapping_Bar : DiscriminatedWithMultiMapping_ ...@@ -165,4 +165,4 @@ private class DiscriminatedWithMultiMapping_Bar : DiscriminatedWithMultiMapping_
public override int Type => 2; public override int Type => 2;
} }
} }
} }
\ No newline at end of file
...@@ -6,7 +6,7 @@ namespace Dapper.Tests ...@@ -6,7 +6,7 @@ namespace Dapper.Tests
public class NullTests : TestBase public class NullTests : TestBase
{ {
[Fact] [Fact]
public void TestNullableDefault() public void TestNullableDefault()
{ {
TestNullable(false); TestNullable(false);
} }
...@@ -17,10 +17,10 @@ public void TestNullableApplyNulls() ...@@ -17,10 +17,10 @@ public void TestNullableApplyNulls()
TestNullable(true); TestNullable(true);
} }
private void TestNullable(bool applyNulls) private void TestNullable(bool applyNulls)
{ {
bool oldSetting = SqlMapper.Settings.ApplyNullValues; bool oldSetting = SqlMapper.Settings.ApplyNullValues;
try try
{ {
SqlMapper.Settings.ApplyNullValues = applyNulls; SqlMapper.Settings.ApplyNullValues = applyNulls;
SqlMapper.PurgeQueryCache(); SqlMapper.PurgeQueryCache();
...@@ -51,7 +51,7 @@ private void TestNullable(bool applyNulls) ...@@ -51,7 +51,7 @@ private void TestNullable(bool applyNulls)
Assert.Equal(AnEnum.B, obj.D); Assert.Equal(AnEnum.B, obj.D);
Assert.Null(obj.E); Assert.Null(obj.E);
} }
else else
{ {
Assert.Equal(2, obj.A); Assert.Equal(2, obj.A);
Assert.Equal(2, obj.B); Assert.Equal(2, obj.B);
...@@ -59,7 +59,8 @@ private void TestNullable(bool applyNulls) ...@@ -59,7 +59,8 @@ private void TestNullable(bool applyNulls)
Assert.Equal(AnEnum.B, obj.D); Assert.Equal(AnEnum.B, obj.D);
Assert.Equal(AnEnum.B, obj.E); Assert.Equal(AnEnum.B, obj.E);
} }
} finally }
finally
{ {
SqlMapper.Settings.ApplyNullValues = oldSetting; SqlMapper.Settings.ApplyNullValues = oldSetting;
} }
...@@ -67,14 +68,14 @@ private void TestNullable(bool applyNulls) ...@@ -67,14 +68,14 @@ private void TestNullable(bool applyNulls)
private class NullTestClass private class NullTestClass
{ {
public int Id { get; set; } public int Id { get; set; }
public int A { get; set; } public int A { get; set; }
public int? B { get; set; } public int? B { get; set; }
public string C { get; set; } public string C { get; set; }
public AnEnum D { get; set; } public AnEnum D { get; set; }
public AnEnum? E { get; set; } public AnEnum? E { get; set; }
public NullTestClass() public NullTestClass()
{ {
A = 2; A = 2;
B = 2; B = 2;
......
...@@ -445,7 +445,7 @@ public void SO29533765_DataTableParametersViaDynamicParameters() ...@@ -445,7 +445,7 @@ public void SO29533765_DataTableParametersViaDynamicParameters()
connection.Execute("create type MyTVPType as table (id int)"); connection.Execute("create type MyTVPType as table (id int)");
connection.Execute("create proc #DataTableParameters @ids MyTVPType readonly as select count(1) from @ids"); connection.Execute("create proc #DataTableParameters @ids MyTVPType readonly as select count(1) from @ids");
var table = new DataTable { TableName="MyTVPType", Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } }; var table = new DataTable { TableName = "MyTVPType", Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } };
table.SetTypeName(table.TableName); // per SO29533765 table.SetTypeName(table.TableName); // per SO29533765
IDictionary<string, object> args = new Dictionary<string, object> IDictionary<string, object> args = new Dictionary<string, object>
{ {
...@@ -1060,8 +1060,9 @@ public void SO25297173_DynamicIn() ...@@ -1060,8 +1060,9 @@ public void SO25297173_DynamicIn()
insert @table values(6); insert @table values(6);
insert @table values(7); insert @table values(7);
SELECT value FROM @table WHERE value IN @myIds"; SELECT value FROM @table WHERE value IN @myIds";
var queryParams = new Dictionary<string, object> { var queryParams = new Dictionary<string, object>
["myIds"] = new [] { 5, 6 } {
["myIds"] = new[] { 5, 6 }
}; };
var dynamicParams = new DynamicParameters(queryParams); var dynamicParams = new DynamicParameters(queryParams);
......
...@@ -11,7 +11,7 @@ public EntityFrameworkTests() ...@@ -11,7 +11,7 @@ public EntityFrameworkTests()
{ {
EntityFramework.Handlers.Register(); EntityFramework.Handlers.Register();
} }
[Fact] [Fact]
public void Issue570_DbGeo_HasValues() public void Issue570_DbGeo_HasValues()
{ {
......
...@@ -44,4 +44,4 @@ public void Issue178_Firebird() ...@@ -44,4 +44,4 @@ public void Issue178_Firebird()
} }
} }
} }
} }
\ No newline at end of file
...@@ -60,4 +60,4 @@ public void TestNoDefaultConstructorBinary() ...@@ -60,4 +60,4 @@ public void TestNoDefaultConstructorBinary()
} }
} }
} }
#endif #endif
\ No newline at end of file
...@@ -269,4 +269,4 @@ public async void Issue457_NullParameterValues_MultiAsync_Named() ...@@ -269,4 +269,4 @@ public async void Issue457_NullParameterValues_MultiAsync_Named()
} }
} }
} }
#endif #endif
\ No newline at end of file
...@@ -53,4 +53,4 @@ public class AuthorCE ...@@ -53,4 +53,4 @@ public class AuthorCE
} }
} }
} }
#endif #endif
\ No newline at end of file
...@@ -145,7 +145,7 @@ public void Issue524_QueryMultiple_Cast() ...@@ -145,7 +145,7 @@ public void Issue524_QueryMultiple_Cast()
Assert.Equal(42, connection.QuerySingle<int>("select cast(42 as bigint)")); Assert.Equal(42, connection.QuerySingle<int>("select cast(42 as bigint)"));
// using multi-reader API // using multi-reader API
using(var reader = connection.QueryMultiple("select cast(42 as bigint); select cast(42 as bigint)")) using (var reader = connection.QueryMultiple("select cast(42 as bigint); select cast(42 as bigint)"))
{ {
Assert.Equal(42, reader.Read<int>().Single()); Assert.Equal(42, reader.Read<int>().Single());
Assert.Equal(42, reader.ReadSingle<int>()); Assert.Equal(42, reader.ReadSingle<int>());
......
...@@ -377,9 +377,9 @@ private RatingValueHandler() ...@@ -377,9 +377,9 @@ private RatingValueHandler()
public override RatingValue Parse(object value) public override RatingValue Parse(object value)
{ {
if (value is Int32) if (value is int)
{ {
return new RatingValue() { Value = (Int32)value }; return new RatingValue() { Value = (int)value };
} }
throw new FormatException("Invalid conversion to RatingValue"); throw new FormatException("Invalid conversion to RatingValue");
...@@ -395,13 +395,13 @@ public override void SetValue(IDbDataParameter parameter, RatingValue value) ...@@ -395,13 +395,13 @@ public override void SetValue(IDbDataParameter parameter, RatingValue value)
public class RatingValue public class RatingValue
{ {
public Int32 Value { get; set; } public int Value { get; set; }
// ... some other properties etc ... // ... some other properties etc ...
} }
public class MyResult public class MyResult
{ {
public String CategoryName { get; set; } public string CategoryName { get; set; }
public RatingValue CategoryRating { get; set; } public RatingValue CategoryRating { get; set; }
} }
...@@ -424,7 +424,7 @@ public void SO24740733_TestCustomValueSingleColumn() ...@@ -424,7 +424,7 @@ public void SO24740733_TestCustomValueSingleColumn()
Assert.Equal(200, foo.Value); Assert.Equal(200, foo.Value);
} }
public class StringListTypeHandler : SqlMapper.TypeHandler<List<String>> public class StringListTypeHandler : SqlMapper.TypeHandler<List<string>>
{ {
private StringListTypeHandler() private StringListTypeHandler()
{ {
...@@ -434,18 +434,18 @@ private StringListTypeHandler() ...@@ -434,18 +434,18 @@ private StringListTypeHandler()
//Just a simple List<string> type handler implementation //Just a simple List<string> type handler implementation
public override void SetValue(IDbDataParameter parameter, List<string> value) public override void SetValue(IDbDataParameter parameter, List<string> value)
{ {
parameter.Value = String.Join(",", value); parameter.Value = string.Join(",", value);
} }
public override List<string> Parse(object value) public override List<string> Parse(object value)
{ {
return ((value as String) ?? "").Split(',').ToList(); return ((value as string) ?? "").Split(',').ToList();
} }
} }
public class MyObjectWithStringList public class MyObjectWithStringList
{ {
public List<String> Names { get; set; } public List<string> Names { get; set; }
} }
[Fact] [Fact]
......
...@@ -5,6 +5,7 @@ VisualStudioVersion = 15.0.26730.8 ...@@ -5,6 +5,7 @@ VisualStudioVersion = 15.0.26730.8
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A34907DF-958A-4E4C-8491-84CF303FD13E}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A34907DF-958A-4E4C-8491-84CF303FD13E}"
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
appveyor.yml = appveyor.yml appveyor.yml = appveyor.yml
build.ps1 = build.ps1 build.ps1 = build.ps1
build.sh = build.sh build.sh = build.sh
......
...@@ -61,7 +61,6 @@ public void AddParameter(IDbCommand command, string name) ...@@ -61,7 +61,6 @@ public void AddParameter(IDbCommand command, string name)
{ {
param = command.CreateParameter(); param = command.CreateParameter();
param.ParameterName = name; param.ParameterName = name;
} }
else else
{ {
......
...@@ -91,7 +91,7 @@ public ConstructorInfo FindConstructor(string[] names, Type[] types) ...@@ -91,7 +91,7 @@ public ConstructorInfo FindConstructor(string[] names, Type[] types)
int i = 0; int i = 0;
for (; i < ctorParameters.Length; i++) for (; i < ctorParameters.Length; i++)
{ {
if (!String.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase)) if (!string.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase))
break; break;
if (types[i] == typeof(byte[]) && ctorParameters[i].ParameterType.FullName == SqlMapper.LinqBinary) if (types[i] == typeof(byte[]) && ctorParameters[i].ParameterType.FullName == SqlMapper.LinqBinary)
continue; continue;
...@@ -152,13 +152,13 @@ public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, ...@@ -152,13 +152,13 @@ public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor,
/// <returns>Mapping implementation</returns> /// <returns>Mapping implementation</returns>
public SqlMapper.IMemberMap GetMember(string columnName) public SqlMapper.IMemberMap GetMember(string columnName)
{ {
var property = Properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.Ordinal)) var property = Properties.Find(p => string.Equals(p.Name, columnName, StringComparison.Ordinal))
?? Properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase)); ?? Properties.Find(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase));
if (property == null && MatchNamesWithUnderscores) if (property == null && MatchNamesWithUnderscores)
{ {
property = Properties.FirstOrDefault(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.Ordinal)) property = Properties.Find(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.Ordinal))
?? Properties.FirstOrDefault(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.OrdinalIgnoreCase)); ?? Properties.Find(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.OrdinalIgnoreCase));
} }
if (property != null) if (property != null)
...@@ -169,20 +169,20 @@ public SqlMapper.IMemberMap GetMember(string columnName) ...@@ -169,20 +169,20 @@ public SqlMapper.IMemberMap GetMember(string columnName)
// preference order is: // preference order is:
// exact match over underscre match, exact case over wrong case, backing fields over regular fields, match-inc-underscores over match-exc-underscores // exact match over underscre match, exact case over wrong case, backing fields over regular fields, match-inc-underscores over match-exc-underscores
var field = _fields.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.Ordinal)) var field = _fields.Find(p => string.Equals(p.Name, columnName, StringComparison.Ordinal))
?? _fields.FirstOrDefault(p => string.Equals(p.Name, backingFieldName, StringComparison.Ordinal)) ?? _fields.Find(p => string.Equals(p.Name, backingFieldName, StringComparison.Ordinal))
?? _fields.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase)) ?? _fields.Find(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase))
?? _fields.FirstOrDefault(p => string.Equals(p.Name, backingFieldName, StringComparison.OrdinalIgnoreCase)); ?? _fields.Find(p => string.Equals(p.Name, backingFieldName, StringComparison.OrdinalIgnoreCase));
if (field == null && MatchNamesWithUnderscores) if (field == null && MatchNamesWithUnderscores)
{ {
var effectiveColumnName = columnName.Replace("_", ""); var effectiveColumnName = columnName.Replace("_", "");
backingFieldName = "<" +effectiveColumnName + ">k__BackingField"; backingFieldName = "<" + effectiveColumnName + ">k__BackingField";
field = _fields.FirstOrDefault(p => string.Equals(p.Name, effectiveColumnName, StringComparison.Ordinal)) field = _fields.Find(p => string.Equals(p.Name, effectiveColumnName, StringComparison.Ordinal))
?? _fields.FirstOrDefault(p => string.Equals(p.Name, backingFieldName, StringComparison.Ordinal)) ?? _fields.Find(p => string.Equals(p.Name, backingFieldName, StringComparison.Ordinal))
?? _fields.FirstOrDefault(p => string.Equals(p.Name, effectiveColumnName, StringComparison.OrdinalIgnoreCase)) ?? _fields.Find(p => string.Equals(p.Name, effectiveColumnName, StringComparison.OrdinalIgnoreCase))
?? _fields.FirstOrDefault(p => string.Equals(p.Name, backingFieldName, StringComparison.OrdinalIgnoreCase)); ?? _fields.Find(p => string.Equals(p.Name, backingFieldName, StringComparison.OrdinalIgnoreCase));
} }
if (field != null) if (field != null)
......
...@@ -394,7 +394,7 @@ public DynamicParameters Output<T>(T target, Expression<Func<T, object>> express ...@@ -394,7 +394,7 @@ public DynamicParameters Output<T>(T target, Expression<Func<T, object>> express
} }
while (diving != null); while (diving != null);
var dynamicParamName = string.Join(string.Empty, names.ToArray()); var dynamicParamName = string.Concat(names.ToArray());
// Before we get all emitty... // Before we get all emitty...
var lookup = string.Join("|", names.ToArray()); var lookup = string.Join("|", names.ToArray());
......
...@@ -407,7 +407,7 @@ private static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, ...@@ -407,7 +407,7 @@ private static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn,
object val = func(reader); object val = func(reader);
if (val == null || val is T) if (val == null || val is T)
{ {
buffer.Add((T) val); buffer.Add((T)val);
} }
else else
{ {
...@@ -564,7 +564,8 @@ private static async Task<int> ExecuteMultiImplAsync(IDbConnection cnn, CommandD ...@@ -564,7 +564,8 @@ private static async Task<int> ExecuteMultiImplAsync(IDbConnection cnn, CommandD
masterSql = cmd.CommandText; masterSql = cmd.CommandText;
var identity = new Identity(command.CommandText, cmd.CommandType, cnn, null, obj.GetType(), null); var identity = new Identity(command.CommandText, cmd.CommandType, cnn, null, obj.GetType(), null);
info = GetCacheInfo(identity, obj, command.AddToCache); info = GetCacheInfo(identity, obj, command.AddToCache);
} else if(pending.Count >= MAX_PENDING) }
else if (pending.Count >= MAX_PENDING)
{ {
var recycled = pending.Dequeue(); var recycled = pending.Dequeue();
total += await recycled.Task.ConfigureAwait(false); total += await recycled.Task.ConfigureAwait(false);
...@@ -955,15 +956,18 @@ private static async Task<IEnumerable<TReturn>> MultiMapAsync<TReturn>(this IDbC ...@@ -955,15 +956,18 @@ private static async Task<IEnumerable<TReturn>> MultiMapAsync<TReturn>(this IDbC
var identity = new Identity(command.CommandText, command.CommandType, cnn, types[0], param?.GetType(), types); var identity = new Identity(command.CommandText, command.CommandType, cnn, types[0], param?.GetType(), types);
var info = GetCacheInfo(identity, param, command.AddToCache); var info = GetCacheInfo(identity, param, command.AddToCache);
bool wasClosed = cnn.State == ConnectionState.Closed; bool wasClosed = cnn.State == ConnectionState.Closed;
try { try
{
if (wasClosed) await ((DbConnection)cnn).OpenAsync().ConfigureAwait(false); if (wasClosed) await ((DbConnection)cnn).OpenAsync().ConfigureAwait(false);
using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader)) using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
using (var reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, command.CancellationToken).ConfigureAwait(false)) { using (var reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, command.CancellationToken).ConfigureAwait(false))
{
var results = MultiMapImpl(null, default(CommandDefinition), types, map, splitOn, reader, identity, true); var results = MultiMapImpl(null, default(CommandDefinition), types, map, splitOn, reader, identity, true);
return command.Buffered ? results.ToList() : results; return command.Buffered ? results.ToList() : results;
} }
} }
finally { finally
{
if (wasClosed) cnn.Close(); if (wasClosed) cnn.Close();
} }
} }
...@@ -1027,8 +1031,9 @@ public static async Task<GridReader> QueryMultipleAsync(this IDbConnection cnn, ...@@ -1027,8 +1031,9 @@ public static async Task<GridReader> QueryMultipleAsync(this IDbConnection cnn,
if (!reader.IsClosed) if (!reader.IsClosed)
{ {
try { cmd.Cancel(); } try { cmd.Cancel(); }
catch { /* don't spoil the existing exception */ catch
} { /* don't spoil the existing exception */
}
} }
reader.Dispose(); reader.Dispose();
} }
......
...@@ -169,7 +169,7 @@ private T ReadRow<T>(Type type, Row row) ...@@ -169,7 +169,7 @@ private T ReadRow<T>(Type type, Row row)
IsConsumed = true; IsConsumed = true;
T result = default(T); T result = default(T);
if(reader.Read() && reader.FieldCount != 0) if (reader.Read() && reader.FieldCount != 0)
{ {
var typedIdentity = identity.ForGrid(type, gridIndex); var typedIdentity = identity.ForGrid(type, gridIndex);
CacheInfo cache = GetCacheInfo(typedIdentity, null, addToCache); CacheInfo cache = GetCacheInfo(typedIdentity, null, addToCache);
...@@ -194,7 +194,7 @@ private T ReadRow<T>(Type type, Row row) ...@@ -194,7 +194,7 @@ private T ReadRow<T>(Type type, Row row)
if ((row & Row.Single) != 0 && reader.Read()) ThrowMultipleRows(row); if ((row & Row.Single) != 0 && reader.Read()) ThrowMultipleRows(row);
while (reader.Read()) { /* ignore subsequent rows */ } while (reader.Read()) { /* ignore subsequent rows */ }
} }
else if((row & Row.FirstOrDefault) == 0) // demanding a row, and don't have one else if ((row & Row.FirstOrDefault) == 0) // demanding a row, and don't have one
{ {
ThrowZeroRows(row); ThrowZeroRows(row);
} }
...@@ -372,9 +372,12 @@ private IEnumerable<T> ReadDeferred<T>(int index, Func<IDataReader, object> dese ...@@ -372,9 +372,12 @@ private IEnumerable<T> ReadDeferred<T>(int index, Func<IDataReader, object> dese
while (index == gridIndex && reader.Read()) while (index == gridIndex && reader.Read())
{ {
object val = deserializer(reader); object val = deserializer(reader);
if (val == null || val is T) { if (val == null || val is T)
{
yield return (T)val; yield return (T)val;
} else { }
else
{
yield return (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture); yield return (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
} }
} }
...@@ -439,4 +442,4 @@ public void Dispose() ...@@ -439,4 +442,4 @@ public void Dispose()
} }
} }
} }
} }
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment