Commit 7e8eab6a authored by Nigrimmist's avatar Nigrimmist

- code improvements

parent b77e5384
...@@ -34,6 +34,7 @@ ...@@ -34,6 +34,7 @@
using System.Globalization; using System.Globalization;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Data.Common; using System.Data.Common;
using System.Data.SqlClient;
namespace Dapper namespace Dapper
{ {
...@@ -89,11 +90,13 @@ internal static CommandDefinition ForCallback(object parameters) ...@@ -89,11 +90,13 @@ internal static CommandDefinition ForCallback(object parameters)
internal void OnCompleted() internal void OnCompleted()
{ {
if (parameters is SqlMapper.IParameterCallbacks) var parametersCallbacks = parameters as SqlMapper.IParameterCallbacks;
if (parametersCallbacks != null)
{ {
((SqlMapper.IParameterCallbacks)parameters).OnCompleted(); parametersCallbacks.OnCompleted();
} }
} }
/// <summary> /// <summary>
/// The command (sql or a stored-procedure name) to execute /// The command (sql or a stored-procedure name) to execute
/// </summary> /// </summary>
...@@ -376,9 +379,10 @@ object ITypeHandler.Parse(Type destinationType, object value) ...@@ -376,9 +379,10 @@ object ITypeHandler.Parse(Type destinationType, object value)
void ITypeHandler.SetValue(IDbDataParameter parameter, object value) void ITypeHandler.SetValue(IDbDataParameter parameter, object value)
{ {
parameter.Value = SanitizeParameterValue(value); parameter.Value = SanitizeParameterValue(value);
if (parameter is System.Data.SqlClient.SqlParameter) var sqlParameter = parameter as SqlParameter;
if (sqlParameter != null)
{ {
((System.Data.SqlClient.SqlParameter)parameter).UdtTypeName = udtTypeName; sqlParameter.UdtTypeName = udtTypeName;
} }
} }
} }
...@@ -2802,7 +2806,7 @@ public static void PackListParameters(IDbCommand command, string namePrefix, obj ...@@ -2802,7 +2806,7 @@ public static void PackListParameters(IDbCommand command, string namePrefix, obj
listParam.Size = -1; listParam.Size = -1;
} }
} }
if (isDbString && item as DbString != null) if (isDbString && item is DbString)
{ {
var str = item as DbString; var str = item as DbString;
str.AddParameter(command, listParam.ParameterName); str.AddParameter(command, listParam.ParameterName);
...@@ -3036,14 +3040,7 @@ internal static IList<LiteralToken> GetLiteralTokens(string sql) ...@@ -3036,14 +3040,7 @@ internal static IList<LiteralToken> GetLiteralTokens(string sql)
var matches = literalTokens.Matches(sql); var matches = literalTokens.Matches(sql);
var found = new HashSet<string>(StringComparer.Ordinal); var found = new HashSet<string>(StringComparer.Ordinal);
List<LiteralToken> list = new List<LiteralToken>(matches.Count); List<LiteralToken> list = new List<LiteralToken>(matches.Count);
foreach(Match match in matches) list.AddRange(from Match match in matches let token = match.Value where found.Add(match.Value) select new LiteralToken(token, match.Groups[1].Value));
{
string token = match.Value;
if(found.Add(match.Value))
{
list.Add(new LiteralToken(token, match.Groups[1].Value));
}
}
return list.Count == 0 ? LiteralToken.None : list; return list.Count == 0 ? LiteralToken.None : list;
} }
...@@ -3095,15 +3092,7 @@ internal static IList<LiteralToken> GetLiteralTokens(string sql) ...@@ -3095,15 +3092,7 @@ internal static IList<LiteralToken> GetLiteralTokens(string sql)
if (ctors.Length == 1 && propsArr.Length == (ctorParams = ctors[0].GetParameters()).Length) if (ctors.Length == 1 && propsArr.Length == (ctorParams = ctors[0].GetParameters()).Length)
{ {
// check if reflection was kind enough to put everything in the right order for us // check if reflection was kind enough to put everything in the right order for us
bool ok = true; bool ok = !propsArr.Where((t, i) => !string.Equals(t.Name, ctorParams[i].Name, StringComparison.OrdinalIgnoreCase)).Any();
for (int i = 0; i < propsArr.Length; i++)
{
if (!string.Equals(propsArr[i].Name, ctorParams[i].Name, StringComparison.OrdinalIgnoreCase))
{
ok = false;
break;
}
}
if(ok) if(ok)
{ {
// pre-sorted; the reflection gods have smiled upon us // pre-sorted; the reflection gods have smiled upon us
...@@ -3494,7 +3483,6 @@ private static IDataReader ExecuteReaderImpl(IDbConnection cnn, ref CommandDefin ...@@ -3494,7 +3483,6 @@ private static IDataReader ExecuteReaderImpl(IDbConnection cnn, ref CommandDefin
{ {
object param = command.Parameters; object param = command.Parameters;
IEnumerable multiExec = GetMultiExec(param); IEnumerable multiExec = GetMultiExec(param);
Identity identity;
CacheInfo info = null; CacheInfo info = null;
if (multiExec != null) if (multiExec != null)
{ {
...@@ -3504,7 +3492,7 @@ private static IDataReader ExecuteReaderImpl(IDbConnection cnn, ref CommandDefin ...@@ -3504,7 +3492,7 @@ private static IDataReader ExecuteReaderImpl(IDbConnection cnn, ref CommandDefin
// nice and simple // nice and simple
if (param != null) if (param != null)
{ {
identity = new Identity(command.CommandText, command.CommandType, cnn, null, param.GetType(), null); var identity = new Identity(command.CommandText, command.CommandType, cnn, null, param.GetType(), null);
info = GetCacheInfo(identity, param, command.AddToCache); info = GetCacheInfo(identity, param, command.AddToCache);
} }
var paramReader = info == null ? null : info.ParamReader; var paramReader = info == null ? null : info.ParamReader;
...@@ -3901,14 +3889,7 @@ public static void SetTypeMap(Type type, ITypeMap map) ...@@ -3901,14 +3889,7 @@ public static void SetTypeMap(Type type, ITypeMap map)
// Store the value in the property/field // Store the value in the property/field
if (item.Property != null) if (item.Property != null)
{ {
if (type.IsValueType()) il.Emit(type.IsValueType() ? OpCodes.Call : OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type));
{
il.Emit(OpCodes.Call, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target]
}
else
{
il.Emit(OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target]
}
} }
else else
{ {
...@@ -4938,7 +4919,6 @@ public DynamicParameters Output<T>(T target, Expression<Func<T, object>> express ...@@ -4938,7 +4919,6 @@ public DynamicParameters Output<T>(T target, Expression<Func<T, object>> express
// Does the chain consist of MemberExpressions leading to a ParameterExpression of type T? // Does the chain consist of MemberExpressions leading to a ParameterExpression of type T?
MemberExpression diving = lastMemberAccess; MemberExpression diving = lastMemberAccess;
ParameterExpression constant = null;
// Retain a list of member names and the member expressions so we can rebuild the chain. // Retain a list of member names and the member expressions so we can rebuild the chain.
List<string> names = new List<string>(); List<string> names = new List<string>();
List<MemberExpression> chain = new List<MemberExpression>(); List<MemberExpression> chain = new List<MemberExpression>();
...@@ -4950,7 +4930,7 @@ public DynamicParameters Output<T>(T target, Expression<Func<T, object>> express ...@@ -4950,7 +4930,7 @@ public DynamicParameters Output<T>(T target, Expression<Func<T, object>> express
names.Insert(0, diving.Member.Name); names.Insert(0, diving.Member.Name);
chain.Insert(0, diving); chain.Insert(0, diving);
constant = diving.Expression as ParameterExpression; var constant = diving.Expression as ParameterExpression;
diving = diving.Expression as MemberExpression; diving = diving.Expression as MemberExpression;
if (constant != null && if (constant != null &&
......
...@@ -111,7 +111,7 @@ private static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, ...@@ -111,7 +111,7 @@ private static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn,
{ {
buffer.Add((T)func(reader)); buffer.Add((T)func(reader));
} }
while (await reader.NextResultAsync().ConfigureAwait(false)) { } while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { }
command.OnCompleted(); command.OnCompleted();
return buffer; return buffer;
} }
......
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
......
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
......
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Data.Common;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
...@@ -26,8 +23,8 @@ public partial class Table<T, TId> ...@@ -26,8 +23,8 @@ public partial class Table<T, TId>
paramNames.Remove("Id"); paramNames.Remove("Id");
string cols = string.Join(",", paramNames); string cols = string.Join(",", paramNames);
string cols_params = string.Join(",", paramNames.Select(p => "@" + p)); string colsParams = string.Join(",", paramNames.Select(p => "@" + p));
var sql = "set nocount on insert " + TableName + " (" + cols + ") values (" + cols_params + ") select cast(scope_identity() as int)"; var sql = "set nocount on insert " + TableName + " (" + cols + ") values (" + colsParams + ") select cast(scope_identity() as int)";
return (await database.QueryAsync<int?>(sql, o).ConfigureAwait(false)).Single(); return (await database.QueryAsync<int?>(sql, o).ConfigureAwait(false)).Single();
} }
......
...@@ -131,7 +131,7 @@ internal static List<string> GetParamNames(object o) ...@@ -131,7 +131,7 @@ internal static List<string> GetParamNames(object o)
{ {
var attribs = prop.GetCustomAttributes(typeof(IgnorePropertyAttribute), true); var attribs = prop.GetCustomAttributes(typeof(IgnorePropertyAttribute), true);
var attr = attribs.FirstOrDefault() as IgnorePropertyAttribute; var attr = attribs.FirstOrDefault() as IgnorePropertyAttribute;
if (attr==null || (attr != null && !attr.Value)) if (attr==null || !attr.Value)
{ {
paramNames.Add(prop.Name); paramNames.Add(prop.Name);
} }
......
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
......
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Web;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
...@@ -78,7 +77,7 @@ static List<PropertyInfo> RelevantProperties() ...@@ -78,7 +77,7 @@ static List<PropertyInfo> RelevantProperties()
private static bool AreEqual<U>(U first, U second) private static bool AreEqual<U>(U first, U second)
{ {
if (first == null && second == null) return true; if (first == null && second == null) return true;
if (first == null && second != null) return false; if (first == null) return false;
return first.Equals(second); return first.Equals(second);
} }
...@@ -171,7 +170,6 @@ private static bool AreEqual<U>(U first, U second) ...@@ -171,7 +170,6 @@ private static bool AreEqual<U>(U first, U second)
// adapted from http://stackoverflow.com/a/966466/17174 // adapted from http://stackoverflow.com/a/966466/17174
private static Func<T, T> GenerateCloner() private static Func<T, T> GenerateCloner()
{ {
Delegate myExec = null;
var dm = new DynamicMethod("DoClone", typeof(T), new Type[] { typeof(T) }, true); var dm = new DynamicMethod("DoClone", typeof(T), new Type[] { typeof(T) }, true);
var ctor = typeof(T).GetConstructor(new Type[] { }); var ctor = typeof(T).GetConstructor(new Type[] { });
...@@ -199,7 +197,7 @@ private static bool AreEqual<U>(U first, U second) ...@@ -199,7 +197,7 @@ private static bool AreEqual<U>(U first, U second)
// Return constructed object. --> 0 items on stack // Return constructed object. --> 0 items on stack
il.Emit(OpCodes.Ret); il.Emit(OpCodes.Ret);
myExec = dm.CreateDelegate(typeof(Func<T, T>)); var myExec = dm.CreateDelegate(typeof(Func<T, T>));
return (Func<T, T>)myExec; return (Func<T, T>)myExec;
} }
......
...@@ -26,9 +26,9 @@ public SqlCompactTable(Database<TDatabase> database, string likelyTableName) ...@@ -26,9 +26,9 @@ public SqlCompactTable(Database<TDatabase> database, string likelyTableName)
paramNames.Remove("Id"); paramNames.Remove("Id");
string cols = string.Join(",", paramNames); string cols = string.Join(",", paramNames);
string cols_params = string.Join(",", paramNames.Select(p => "@" + p)); string colsParams = string.Join(",", paramNames.Select(p => "@" + p));
var sql = "insert " + TableName + " (" + cols + ") values (" + cols_params + ")"; var sql = "insert " + TableName + " (" + cols + ") values (" + colsParams + ")";
if (database.Execute(sql, o) != 1) if (database.Execute(sql, o) != 1)
{ {
return null; return null;
......
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
......
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
......
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
namespace Dapper namespace Dapper
{ {
...@@ -106,7 +104,7 @@ public Template AddTemplate(string sql, dynamic parameters = null) ...@@ -106,7 +104,7 @@ public Template AddTemplate(string sql, dynamic parameters = null)
return new Template(this, sql, parameters); return new Template(this, sql, parameters);
} }
void AddClause(string name, string sql, object parameters, string joiner, string prefix = "", string postfix = "", bool IsInclusive = false) void AddClause(string name, string sql, object parameters, string joiner, string prefix = "", string postfix = "", bool isInclusive = false)
{ {
Clauses clauses; Clauses clauses;
if (!data.TryGetValue(name, out clauses)) if (!data.TryGetValue(name, out clauses))
...@@ -114,7 +112,7 @@ void AddClause(string name, string sql, object parameters, string joiner, string ...@@ -114,7 +112,7 @@ void AddClause(string name, string sql, object parameters, string joiner, string
clauses = new Clauses(joiner, prefix, postfix); clauses = new Clauses(joiner, prefix, postfix);
data[name] = clauses; data[name] = clauses;
} }
clauses.Add(new Clause { Sql = sql, Parameters = parameters, IsInclusive = IsInclusive }); clauses.Add(new Clause { Sql = sql, Parameters = parameters, IsInclusive = isInclusive });
seq++; seq++;
} }
...@@ -150,7 +148,7 @@ public SqlBuilder Where(string sql, dynamic parameters = null) ...@@ -150,7 +148,7 @@ public SqlBuilder Where(string sql, dynamic parameters = null)
public SqlBuilder OrWhere(string sql, dynamic parameters = null) public SqlBuilder OrWhere(string sql, dynamic parameters = null)
{ {
AddClause("where", sql, parameters, " AND ", prefix: "WHERE ", postfix: "\n", IsInclusive: true); AddClause("where", sql, parameters, " AND ", prefix: "WHERE ", postfix: "\n", isInclusive: true);
return this; return this;
} }
......
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
......
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
#if DNXCORE50 #if DNXCORE50
using ApplicationException = global::System.InvalidOperationException; using ApplicationException = global::System.InvalidOperationException;
......
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.Configuration;
using System.Data; using System.Data;
using System.Data.Common; using System.Data.Common;
using System.Dynamic; using System.Dynamic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
namespace Massive namespace Massive
{ {
...@@ -37,13 +34,13 @@ public static void AddParam(this DbCommand cmd, object item) ...@@ -37,13 +34,13 @@ public static void AddParam(this DbCommand cmd, object item)
} }
else else
{ {
if (item.GetType() == typeof(Guid)) if (item is Guid)
{ {
p.Value = item.ToString(); p.Value = item.ToString();
p.DbType = DbType.String; p.DbType = DbType.String;
p.Size = 4000; p.Size = 4000;
} }
else if (item.GetType() == typeof(ExpandoObject)) else if (item is ExpandoObject)
{ {
var d = (IDictionary<string, object>)item; var d = (IDictionary<string, object>)item;
p.Value = d.Values.FirstOrDefault(); p.Value = d.Values.FirstOrDefault();
...@@ -53,7 +50,7 @@ public static void AddParam(this DbCommand cmd, object item) ...@@ -53,7 +50,7 @@ public static void AddParam(this DbCommand cmd, object item)
p.Value = item; p.Value = item;
} }
//from DataChomp //from DataChomp
if (item.GetType() == typeof(string)) if (item is string)
p.Size = 4000; p.Size = 4000;
} }
cmd.Parameters.Add(p); cmd.Parameters.Add(p);
...@@ -85,7 +82,7 @@ public static dynamic ToExpando(this object o) ...@@ -85,7 +82,7 @@ public static dynamic ToExpando(this object o)
{ {
var result = new ExpandoObject(); var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case if (o is ExpandoObject) return o; //shouldn't have to... but just in case
if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection)))
{ {
var nv = (NameValueCollection)o; var nv = (NameValueCollection)o;
...@@ -151,7 +148,7 @@ public virtual IEnumerable<dynamic> Query(string sql, params object[] args) ...@@ -151,7 +148,7 @@ public virtual IEnumerable<dynamic> Query(string sql, params object[] args)
var rdr = CreateCommand(sql, conn, args).ExecuteReader(); var rdr = CreateCommand(sql, conn, args).ExecuteReader();
while (rdr.Read()) while (rdr.Read())
{ {
yield return rdr.RecordToExpando(); ; yield return rdr.RecordToExpando();
} }
} }
} }
...@@ -161,7 +158,7 @@ public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, p ...@@ -161,7 +158,7 @@ public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, p
{ {
while (rdr.Read()) while (rdr.Read())
{ {
yield return rdr.RecordToExpando(); ; yield return rdr.RecordToExpando();
} }
} }
...@@ -420,7 +417,7 @@ public virtual dynamic Paged(string where = "", string orderBy = "", string colu ...@@ -420,7 +417,7 @@ public virtual dynamic Paged(string where = "", string orderBy = "", string colu
where = "WHERE " + where; where = "WHERE " + where;
} }
} }
var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where); var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, orderBy, TableName, where);
var pageStart = (currentPage - 1) * pageSize; var pageStart = (currentPage - 1) * pageSize;
sql += string.Format(" WHERE Row >={0} AND Row <={1}", pageStart, (pageStart + pageSize)); sql += string.Format(" WHERE Row >={0} AND Row <={1}", pageStart, (pageStart + pageSize));
countSQL += where; countSQL += where;
......
using System.Data; using NHibernate;
using NHibernate;
using NHibernate.Cfg; using NHibernate.Cfg;
namespace SqlMapper.NHibernate namespace SqlMapper.NHibernate
......
...@@ -174,8 +174,7 @@ public void Run(int iterations) ...@@ -174,8 +174,7 @@ public void Run(int iterations)
var nhSession4 = NHibernateHelper.OpenSession(); var nhSession4 = NHibernateHelper.OpenSession();
tests.Add(id => nhSession4 tests.Add(id => nhSession4
.Query<Post>() .Query<Post>().First(p => p.Id == id), "NHibernate LINQ");
.Where(p => p.Id == id).First(), "NHibernate LINQ");
var nhSession5 = NHibernateHelper.OpenSession(); var nhSession5 = NHibernateHelper.OpenSession();
tests.Add(id => nhSession5.Get<Post>(id), "NHibernate Session.Get"); tests.Add(id => nhSession5.Get<Post>(id), "NHibernate Session.Get");
...@@ -314,7 +313,7 @@ public static string GetNullableString(this SqlDataReader reader, int index) ...@@ -314,7 +313,7 @@ public static string GetNullableString(this SqlDataReader reader, int index)
return null; return null;
} }
public static Nullable<T> GetNullableValue<T>(this SqlDataReader reader, int index) where T : struct public static T? GetNullableValue<T>(this SqlDataReader reader, int index) where T : struct
{ {
object tmp = reader.GetValue(index); object tmp = reader.GetValue(index);
if (tmp != DBNull.Value) if (tmp != DBNull.Value)
......
...@@ -283,13 +283,13 @@ static void AddParam(DbCommand cmd, object item, string ParameterPrefix) ...@@ -283,13 +283,13 @@ static void AddParam(DbCommand cmd, object item, string ParameterPrefix)
} }
else else
{ {
if (item.GetType() == typeof(Guid)) if (item is Guid)
{ {
p.Value = item.ToString(); p.Value = item.ToString();
p.DbType = DbType.String; p.DbType = DbType.String;
p.Size = 4000; p.Size = 4000;
} }
else if (item.GetType() == typeof(string)) else if (item is string)
{ {
p.Size = (item as string).Length + 1; p.Size = (item as string).Length + 1;
if (p.Size < 4000) if (p.Size < 4000)
...@@ -344,13 +344,13 @@ public DbCommand CreateCommand(DbConnection connection, string sql, params objec ...@@ -344,13 +344,13 @@ public DbCommand CreateCommand(DbConnection connection, string sql, params objec
} }
else else
{ {
if (item.GetType() == typeof(Guid)) if (item is Guid)
{ {
p.Value = item.ToString(); p.Value = item.ToString();
p.DbType = DbType.String; p.DbType = DbType.String;
p.Size = 4000; p.Size = 4000;
} }
else if (item.GetType() == typeof(string)) else if (item is string)
{ {
p.Size = (item as string).Length + 1; p.Size = (item as string).Length + 1;
if (p.Size < 4000) if (p.Size < 4000)
...@@ -1034,7 +1034,7 @@ public string LastCommand ...@@ -1034,7 +1034,7 @@ public string LastCommand
sb.Append("\r\n\r\n"); sb.Append("\r\n\r\n");
for (int i = 0; i < _lastArgs.Length; i++) for (int i = 0; i < _lastArgs.Length; i++)
{ {
sb.AppendFormat("{0} - {1}\r\n", i, _lastArgs[i].ToString()); sb.AppendFormat("{0} - {1}\r\n", i, _lastArgs[i]);
} }
} }
return sb.ToString(); return sb.ToString();
...@@ -1185,13 +1185,13 @@ public PocoData(Type t) ...@@ -1185,13 +1185,13 @@ public PocoData(Type t)
// Standard DateTime->Utc mapper // Standard DateTime->Utc mapper
if (ForceDateTimesToUtc && converter == null && srcType == typeof(DateTime) && (dstType == typeof(DateTime) || dstType == typeof(DateTime?))) if (ForceDateTimesToUtc && converter == null && srcType == typeof(DateTime) && (dstType == typeof(DateTime) || dstType == typeof(DateTime?)))
{ {
converter = delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Utc); }; converter = src => new DateTime(((DateTime) src).Ticks, DateTimeKind.Utc);
} }
// Forced type conversion // Forced type conversion
if (converter == null && !dstType.IsAssignableFrom(srcType)) if (converter == null && !dstType.IsAssignableFrom(srcType))
{ {
converter = delegate(object src) { return Convert.ChangeType(src, dstType, null); }; converter = src => Convert.ChangeType(src, dstType, null);
} }
// Fast // Fast
...@@ -1222,11 +1222,10 @@ public PocoData(Type t) ...@@ -1222,11 +1222,10 @@ public PocoData(Type t)
if (!Handled) if (!Handled)
{ {
// Setup stack for call to converter // Setup stack for call to converter
int converterIndex = -1; if (converter != null)
if (converter != null)
{ {
// Add the converter // Add the converter
converterIndex = m_Converters.Count; var converterIndex = m_Converters.Count;
m_Converters.Add(converter); m_Converters.Add(converter);
// Generate IL to push the converter onto the stack // Generate IL to push the converter onto the stack
......
...@@ -175,7 +175,7 @@ private static void RunTests<T>(ref int fail, ref int skip, ref int pass, ref in ...@@ -175,7 +175,7 @@ private static void RunTests<T>(ref int fail, ref int skip, ref int pass, ref in
{ {
MethodInfo[] methods = typeof(T).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); MethodInfo[] methods = typeof(T).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
var activeTests = methods.Where(m => HasAttribute<ActiveTestAttribute>(m)).ToArray(); var activeTests = methods.Where(HasAttribute<ActiveTestAttribute>).ToArray();
if (activeTests.Length != 0) methods = activeTests; if (activeTests.Length != 0) methods = activeTests;
foreach (var method in methods) foreach (var method in methods)
{ {
......
...@@ -141,12 +141,8 @@ public partial class Post: IActiveRecord ...@@ -141,12 +141,8 @@ public partial class Post: IActiveRecord
internal static IRepository<Post> GetRepo(string connectionString, string providerName){ internal static IRepository<Post> GetRepo(string connectionString, string providerName){
SubSonic.tempdbDB db; tempdbDB db;
if(String.IsNullOrEmpty(connectionString)){ db = String.IsNullOrEmpty(connectionString) ? new tempdbDB() : new tempdbDB(connectionString, providerName);
db=new SubSonic.tempdbDB();
}else{
db=new SubSonic.tempdbDB(connectionString, providerName);
}
IRepository<Post> _repo; IRepository<Post> _repo;
if(db.TestMode){ if(db.TestMode){
...@@ -166,7 +162,7 @@ public partial class Post: IActiveRecord ...@@ -166,7 +162,7 @@ public partial class Post: IActiveRecord
var repo = GetRepo(); var repo = GetRepo();
var results=repo.Find(expression); var results=repo.Find(expression);
Post single=null; Post single=null;
if(results.Count() > 0){ if(results.Any()){
single=results.ToList()[0]; single=results.ToList()[0];
single.OnLoaded(); single.OnLoaded();
single.SetIsLoaded(true); single.SetIsLoaded(true);
...@@ -180,7 +176,7 @@ public partial class Post: IActiveRecord ...@@ -180,7 +176,7 @@ public partial class Post: IActiveRecord
var repo = GetRepo(connectionString,providerName); var repo = GetRepo(connectionString,providerName);
var results=repo.Find(expression); var results=repo.Find(expression);
Post single=null; Post single=null;
if(results.Count() > 0){ if(results.Any()){
single=results.ToList()[0]; single=results.ToList()[0];
} }
...@@ -255,7 +251,7 @@ public object KeyValue() ...@@ -255,7 +251,7 @@ public object KeyValue()
} }
public override string ToString(){ public override string ToString(){
return this.Text.ToString(); return this.Text;
} }
public override bool Equals(object obj){ public override bool Equals(object obj){
...@@ -274,7 +270,7 @@ public object KeyValue() ...@@ -274,7 +270,7 @@ public object KeyValue()
public string DescriptorValue() public string DescriptorValue()
{ {
return this.Text.ToString(); return this.Text;
} }
public string DescriptorColumn() { public string DescriptorColumn() {
......
...@@ -31,14 +31,9 @@ public bool TestMode ...@@ -31,14 +31,9 @@ public bool TestMode
} }
} }
public tempdbDB() public tempdbDB()
{ {
if (DefaultDataProvider == null) { DataProvider = DefaultDataProvider ?? ProviderFactory.GetProvider("Smackdown.Properties.Settings.tempdbConnectionString");
DataProvider = ProviderFactory.GetProvider("Smackdown.Properties.Settings.tempdbConnectionString");
}
else {
DataProvider = DefaultDataProvider;
}
Init(); Init();
} }
......
using System;
using SubSonic.Schema; using SubSonic.Schema;
using System.Collections.Generic;
using SubSonic.DataProviders; using SubSonic.DataProviders;
using System.Data; using System.Data;
......
...@@ -20,7 +20,6 @@ ...@@ -20,7 +20,6 @@
using System.Dynamic; using System.Dynamic;
using System.ComponentModel; using System.ComponentModel;
using Microsoft.CSharp.RuntimeBinder; using Microsoft.CSharp.RuntimeBinder;
using System.Data.Common;
using System.Globalization; using System.Globalization;
using System.Threading; using System.Threading;
using System.Data.SqlTypes; using System.Data.SqlTypes;
...@@ -407,7 +406,7 @@ public void TestSchemaChangedMultiMap() ...@@ -407,7 +406,7 @@ public void TestSchemaChangedMultiMap()
connection.Execute("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')"); connection.Execute("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')");
try try
{ {
var tuple = connection.Query<Dog, Dog, Tuple<Dog, Dog>>("select * from #dog d1 join #dog d2 on 1=1", (d1, d2) => Tuple.Create(d1, d2), splitOn: "Age").Single(); var tuple = connection.Query<Dog, Dog, Tuple<Dog, Dog>>("select * from #dog d1 join #dog d2 on 1=1", Tuple.Create, splitOn: "Age").Single();
tuple.Item1.Name.IsEqualTo("Alf"); tuple.Item1.Name.IsEqualTo("Alf");
tuple.Item1.Age.IsEqualTo(1); tuple.Item1.Age.IsEqualTo(1);
...@@ -415,7 +414,7 @@ public void TestSchemaChangedMultiMap() ...@@ -415,7 +414,7 @@ public void TestSchemaChangedMultiMap()
tuple.Item2.Age.IsEqualTo(1); tuple.Item2.Age.IsEqualTo(1);
connection.Execute("alter table #dog drop column Name"); connection.Execute("alter table #dog drop column Name");
tuple = connection.Query<Dog, Dog, Tuple<Dog, Dog>>("select * from #dog d1 join #dog d2 on 1=1", (d1, d2) => Tuple.Create(d1, d2), splitOn: "Age").Single(); tuple = connection.Query<Dog, Dog, Tuple<Dog, Dog>>("select * from #dog d1 join #dog d2 on 1=1", Tuple.Create, splitOn: "Age").Single();
tuple.Item1.Name.IsNull(); tuple.Item1.Name.IsNull();
tuple.Item1.Age.IsEqualTo(1); tuple.Item1.Age.IsEqualTo(1);
...@@ -1573,7 +1572,7 @@ public void TestFlexibleMultiMapping() ...@@ -1573,7 +1572,7 @@ public void TestFlexibleMultiMapping()
3 as Id, 'fred' as Name 3 as Id, 'fred' as Name
"; ";
var personWithAddress = connection.Query<Person, Address, Extra, Tuple<Person, Address, Extra>> var personWithAddress = connection.Query<Person, Address, Extra, Tuple<Person, Address, Extra>>
(sql, (p, a, e) => Tuple.Create(p, a, e), splitOn: "AddressId,Id").First(); (sql, Tuple.Create, splitOn: "AddressId,Id").First();
personWithAddress.Item1.PersonId.IsEqualTo(1); personWithAddress.Item1.PersonId.IsEqualTo(1);
personWithAddress.Item1.Name.IsEqualTo("bob"); personWithAddress.Item1.Name.IsEqualTo("bob");
...@@ -1593,7 +1592,7 @@ public void TestMultiMappingWithSplitOnSpaceBetweenCommas() ...@@ -1593,7 +1592,7 @@ public void TestMultiMappingWithSplitOnSpaceBetweenCommas()
3 as Id, 'fred' as Name 3 as Id, 'fred' as Name
"; ";
var personWithAddress = connection.Query<Person, Address, Extra, Tuple<Person, Address, Extra>> var personWithAddress = connection.Query<Person, Address, Extra, Tuple<Person, Address, Extra>>
(sql, (p, a, e) => Tuple.Create(p, a, e), splitOn: "AddressId, Id").First(); (sql, Tuple.Create, splitOn: "AddressId, Id").First();
personWithAddress.Item1.PersonId.IsEqualTo(1); personWithAddress.Item1.PersonId.IsEqualTo(1);
personWithAddress.Item1.Name.IsEqualTo("bob"); personWithAddress.Item1.Name.IsEqualTo("bob");
...@@ -2130,7 +2129,7 @@ class Bar1 ...@@ -2130,7 +2129,7 @@ class Bar1
} }
public void TestMultiMapperIsNotConfusedWithUnorderedCols() public void TestMultiMapperIsNotConfusedWithUnorderedCols()
{ {
var result = connection.Query<Foo1, Bar1, Tuple<Foo1, Bar1>>("select 1 as Id, 2 as BarId, 3 as BarId, 'a' as Name", (f, b) => Tuple.Create(f, b), splitOn: "BarId").First(); var result = connection.Query<Foo1, Bar1, Tuple<Foo1, Bar1>>("select 1 as Id, 2 as BarId, 3 as BarId, 'a' as Name", Tuple.Create, splitOn: "BarId").First();
result.Item1.Id.IsEqualTo(1); result.Item1.Id.IsEqualTo(1);
result.Item1.BarId.IsEqualTo(2); result.Item1.BarId.IsEqualTo(2);
...@@ -2534,7 +2533,7 @@ public void TestCustomTypeMap() ...@@ -2534,7 +2533,7 @@ public void TestCustomTypeMap()
// custom mapping // custom mapping
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping), var map = new CustomPropertyTypeMap(typeof(TypeWithMapping),
(type, columnName) => type.GetProperties().Where(prop => GetDescriptionFromAttribute(prop) == columnName).FirstOrDefault()); (type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map); Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);
item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single(); item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single();
...@@ -2837,10 +2836,7 @@ public void TestIssue131() ...@@ -2837,10 +2836,7 @@ public void TestIssue131()
{ {
var results = connection.Query<dynamic, int, dynamic>( var results = connection.Query<dynamic, int, dynamic>(
"SELECT 1 Id, 'Mr' Title, 'John' Surname, 4 AddressCount", "SELECT 1 Id, 'Mr' Title, 'John' Surname, 4 AddressCount",
(person, addressCount) => (person, addressCount) => person,
{
return person;
},
splitOn: "AddressCount" splitOn: "AddressCount"
).FirstOrDefault(); ).FirstOrDefault();
......
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