提交 7e8eab6a 编写于 作者: N Nigrimmist

- code improvements

上级 b77e5384
......@@ -34,6 +34,7 @@
using System.Globalization;
using System.Linq.Expressions;
using System.Data.Common;
using System.Data.SqlClient;
namespace Dapper
{
......@@ -89,11 +90,13 @@ internal static CommandDefinition ForCallback(object parameters)
internal void OnCompleted()
{
if (parameters is SqlMapper.IParameterCallbacks)
var parametersCallbacks = parameters as SqlMapper.IParameterCallbacks;
if (parametersCallbacks != null)
{
((SqlMapper.IParameterCallbacks)parameters).OnCompleted();
parametersCallbacks.OnCompleted();
}
}
/// <summary>
/// The command (sql or a stored-procedure name) to execute
/// </summary>
......@@ -376,9 +379,10 @@ object ITypeHandler.Parse(Type destinationType, object value)
void ITypeHandler.SetValue(IDbDataParameter parameter, object 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
listParam.Size = -1;
}
}
if (isDbString && item as DbString != null)
if (isDbString && item is DbString)
{
var str = item as DbString;
str.AddParameter(command, listParam.ParameterName);
......@@ -3036,14 +3040,7 @@ internal static IList<LiteralToken> GetLiteralTokens(string sql)
var matches = literalTokens.Matches(sql);
var found = new HashSet<string>(StringComparer.Ordinal);
List<LiteralToken> list = new List<LiteralToken>(matches.Count);
foreach(Match match in matches)
{
string token = match.Value;
if(found.Add(match.Value))
{
list.Add(new LiteralToken(token, match.Groups[1].Value));
}
}
list.AddRange(from Match match in matches let token = match.Value where found.Add(match.Value) select new LiteralToken(token, match.Groups[1].Value));
return list.Count == 0 ? LiteralToken.None : list;
}
......@@ -3095,15 +3092,7 @@ internal static IList<LiteralToken> GetLiteralTokens(string sql)
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
bool ok = true;
for (int i = 0; i < propsArr.Length; i++)
{
if (!string.Equals(propsArr[i].Name, ctorParams[i].Name, StringComparison.OrdinalIgnoreCase))
{
ok = false;
break;
}
}
bool ok = !propsArr.Where((t, i) => !string.Equals(t.Name, ctorParams[i].Name, StringComparison.OrdinalIgnoreCase)).Any();
if(ok)
{
// pre-sorted; the reflection gods have smiled upon us
......@@ -3494,7 +3483,6 @@ private static IDataReader ExecuteReaderImpl(IDbConnection cnn, ref CommandDefin
{
object param = command.Parameters;
IEnumerable multiExec = GetMultiExec(param);
Identity identity;
CacheInfo info = null;
if (multiExec != null)
{
......@@ -3504,7 +3492,7 @@ private static IDataReader ExecuteReaderImpl(IDbConnection cnn, ref CommandDefin
// nice and simple
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);
}
var paramReader = info == null ? null : info.ParamReader;
......@@ -3901,14 +3889,7 @@ public static void SetTypeMap(Type type, ITypeMap map)
// Store the value in the property/field
if (item.Property != null)
{
if (type.IsValueType())
{
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]
}
il.Emit(type.IsValueType() ? OpCodes.Call : OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type));
}
else
{
......@@ -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?
MemberExpression diving = lastMemberAccess;
ParameterExpression constant = null;
// Retain a list of member names and the member expressions so we can rebuild the chain.
List<string> names = new List<string>();
List<MemberExpression> chain = new List<MemberExpression>();
......@@ -4950,7 +4930,7 @@ public DynamicParameters Output<T>(T target, Expression<Func<T, object>> express
names.Insert(0, diving.Member.Name);
chain.Insert(0, diving);
constant = diving.Expression as ParameterExpression;
var constant = diving.Expression as ParameterExpression;
diving = diving.Expression as MemberExpression;
if (constant != null &&
......
......@@ -111,7 +111,7 @@ private static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn,
{
buffer.Add((T)func(reader));
}
while (await reader.NextResultAsync().ConfigureAwait(false)) { }
while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { }
command.OnCompleted();
return buffer;
}
......
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
......
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
......
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
......@@ -26,8 +23,8 @@ public partial class Table<T, TId>
paramNames.Remove("Id");
string cols = string.Join(",", paramNames);
string cols_params = string.Join(",", paramNames.Select(p => "@" + p));
var sql = "set nocount on insert " + TableName + " (" + cols + ") values (" + cols_params + ") select cast(scope_identity() as int)";
string colsParams = string.Join(",", paramNames.Select(p => "@" + p));
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();
}
......
......@@ -131,7 +131,7 @@ internal static List<string> GetParamNames(object o)
{
var attribs = prop.GetCustomAttributes(typeof(IgnorePropertyAttribute), true);
var attr = attribs.FirstOrDefault() as IgnorePropertyAttribute;
if (attr==null || (attr != null && !attr.Value))
if (attr==null || !attr.Value)
{
paramNames.Add(prop.Name);
}
......
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
......
......@@ -6,7 +6,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Reflection.Emit;
......@@ -78,7 +77,7 @@ static List<PropertyInfo> RelevantProperties()
private static bool AreEqual<U>(U first, U second)
{
if (first == null && second == null) return true;
if (first == null && second != null) return false;
if (first == null) return false;
return first.Equals(second);
}
......@@ -171,7 +170,6 @@ private static bool AreEqual<U>(U first, U second)
// adapted from http://stackoverflow.com/a/966466/17174
private static Func<T, T> GenerateCloner()
{
Delegate myExec = null;
var dm = new DynamicMethod("DoClone", typeof(T), new Type[] { typeof(T) }, true);
var ctor = typeof(T).GetConstructor(new Type[] { });
......@@ -199,7 +197,7 @@ private static bool AreEqual<U>(U first, U second)
// Return constructed object. --> 0 items on stack
il.Emit(OpCodes.Ret);
myExec = dm.CreateDelegate(typeof(Func<T, T>));
var myExec = dm.CreateDelegate(typeof(Func<T, T>));
return (Func<T, T>)myExec;
}
......
......@@ -26,9 +26,9 @@ public SqlCompactTable(Database<TDatabase> database, string likelyTableName)
paramNames.Remove("Id");
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)
{
return null;
......
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
......
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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.Text;
namespace Dapper
{
......@@ -106,7 +104,7 @@ public Template AddTemplate(string sql, dynamic parameters = null)
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;
if (!data.TryGetValue(name, out clauses))
......@@ -114,7 +112,7 @@ void AddClause(string name, string sql, object parameters, string joiner, string
clauses = new Clauses(joiner, prefix, postfix);
data[name] = clauses;
}
clauses.Add(new Clause { Sql = sql, Parameters = parameters, IsInclusive = IsInclusive });
clauses.Add(new Clause { Sql = sql, Parameters = parameters, IsInclusive = isInclusive });
seq++;
}
......@@ -150,7 +148,7 @@ public SqlBuilder Where(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;
}
......
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if DNXCORE50
using ApplicationException = global::System.InvalidOperationException;
......
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
namespace Massive
{
......@@ -37,13 +34,13 @@ public static void AddParam(this DbCommand cmd, object item)
}
else
{
if (item.GetType() == typeof(Guid))
if (item is Guid)
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(ExpandoObject))
else if (item is ExpandoObject)
{
var d = (IDictionary<string, object>)item;
p.Value = d.Values.FirstOrDefault();
......@@ -53,7 +50,7 @@ public static void AddParam(this DbCommand cmd, object item)
p.Value = item;
}
//from DataChomp
if (item.GetType() == typeof(string))
if (item is string)
p.Size = 4000;
}
cmd.Parameters.Add(p);
......@@ -85,7 +82,7 @@ public static dynamic ToExpando(this object o)
{
var result = new ExpandoObject();
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)))
{
var nv = (NameValueCollection)o;
......@@ -151,7 +148,7 @@ public virtual IEnumerable<dynamic> Query(string sql, params object[] args)
var rdr = CreateCommand(sql, conn, args).ExecuteReader();
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
{
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
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;
sql += string.Format(" WHERE Row >={0} AND Row <={1}", pageStart, (pageStart + pageSize));
countSQL += where;
......
using System.Data;
using NHibernate;
using NHibernate;
using NHibernate.Cfg;
namespace SqlMapper.NHibernate
......
......@@ -174,8 +174,7 @@ public void Run(int iterations)
var nhSession4 = NHibernateHelper.OpenSession();
tests.Add(id => nhSession4
.Query<Post>()
.Where(p => p.Id == id).First(), "NHibernate LINQ");
.Query<Post>().First(p => p.Id == id), "NHibernate LINQ");
var nhSession5 = NHibernateHelper.OpenSession();
tests.Add(id => nhSession5.Get<Post>(id), "NHibernate Session.Get");
......@@ -314,7 +313,7 @@ public static string GetNullableString(this SqlDataReader reader, int index)
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);
if (tmp != DBNull.Value)
......
......@@ -283,13 +283,13 @@ static void AddParam(DbCommand cmd, object item, string ParameterPrefix)
}
else
{
if (item.GetType() == typeof(Guid))
if (item is Guid)
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(string))
else if (item is string)
{
p.Size = (item as string).Length + 1;
if (p.Size < 4000)
......@@ -344,13 +344,13 @@ public DbCommand CreateCommand(DbConnection connection, string sql, params objec
}
else
{
if (item.GetType() == typeof(Guid))
if (item is Guid)
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(string))
else if (item is string)
{
p.Size = (item as string).Length + 1;
if (p.Size < 4000)
......@@ -1034,7 +1034,7 @@ public string LastCommand
sb.Append("\r\n\r\n");
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();
......@@ -1185,13 +1185,13 @@ public PocoData(Type t)
// Standard DateTime->Utc mapper
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
if (converter == null && !dstType.IsAssignableFrom(srcType))
{
converter = delegate(object src) { return Convert.ChangeType(src, dstType, null); };
converter = src => Convert.ChangeType(src, dstType, null);
}
// Fast
......@@ -1222,11 +1222,10 @@ public PocoData(Type t)
if (!Handled)
{
// Setup stack for call to converter
int converterIndex = -1;
if (converter != null)
if (converter != null)
{
// Add the converter
converterIndex = m_Converters.Count;
var converterIndex = m_Converters.Count;
m_Converters.Add(converter);
// 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
{
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;
foreach (var method in methods)
{
......
......@@ -141,12 +141,8 @@ public partial class Post: IActiveRecord
internal static IRepository<Post> GetRepo(string connectionString, string providerName){
SubSonic.tempdbDB db;
if(String.IsNullOrEmpty(connectionString)){
db=new SubSonic.tempdbDB();
}else{
db=new SubSonic.tempdbDB(connectionString, providerName);
}
tempdbDB db;
db = String.IsNullOrEmpty(connectionString) ? new tempdbDB() : new tempdbDB(connectionString, providerName);
IRepository<Post> _repo;
if(db.TestMode){
......@@ -166,7 +162,7 @@ public partial class Post: IActiveRecord
var repo = GetRepo();
var results=repo.Find(expression);
Post single=null;
if(results.Count() > 0){
if(results.Any()){
single=results.ToList()[0];
single.OnLoaded();
single.SetIsLoaded(true);
......@@ -180,7 +176,7 @@ public partial class Post: IActiveRecord
var repo = GetRepo(connectionString,providerName);
var results=repo.Find(expression);
Post single=null;
if(results.Count() > 0){
if(results.Any()){
single=results.ToList()[0];
}
......@@ -255,7 +251,7 @@ public object KeyValue()
}
public override string ToString(){
return this.Text.ToString();
return this.Text;
}
public override bool Equals(object obj){
......@@ -274,7 +270,7 @@ public object KeyValue()
public string DescriptorValue()
{
return this.Text.ToString();
return this.Text;
}
public string DescriptorColumn() {
......
......@@ -31,14 +31,9 @@ public bool TestMode
}
}
public tempdbDB()
public tempdbDB()
{
if (DefaultDataProvider == null) {
DataProvider = ProviderFactory.GetProvider("Smackdown.Properties.Settings.tempdbConnectionString");
}
else {
DataProvider = DefaultDataProvider;
}
DataProvider = DefaultDataProvider ?? ProviderFactory.GetProvider("Smackdown.Properties.Settings.tempdbConnectionString");
Init();
}
......
using System;
using SubSonic.Schema;
using System.Collections.Generic;
using SubSonic.DataProviders;
using System.Data;
......
......@@ -20,7 +20,6 @@
using System.Dynamic;
using System.ComponentModel;
using Microsoft.CSharp.RuntimeBinder;
using System.Data.Common;
using System.Globalization;
using System.Threading;
using System.Data.SqlTypes;
......@@ -407,7 +406,7 @@ public void TestSchemaChangedMultiMap()
connection.Execute("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')");
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.Age.IsEqualTo(1);
......@@ -415,7 +414,7 @@ public void TestSchemaChangedMultiMap()
tuple.Item2.Age.IsEqualTo(1);
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.Age.IsEqualTo(1);
......@@ -1573,7 +1572,7 @@ public void TestFlexibleMultiMapping()
3 as Id, 'fred' as Name
";
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.Name.IsEqualTo("bob");
......@@ -1593,7 +1592,7 @@ public void TestMultiMappingWithSplitOnSpaceBetweenCommas()
3 as Id, 'fred' as Name
";
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.Name.IsEqualTo("bob");
......@@ -2130,7 +2129,7 @@ class Bar1
}
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.BarId.IsEqualTo(2);
......@@ -2534,7 +2533,7 @@ public void TestCustomTypeMap()
// custom mapping
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);
item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single();
......@@ -2837,10 +2836,7 @@ public void TestIssue131()
{
var results = connection.Query<dynamic, int, dynamic>(
"SELECT 1 Id, 'Mr' Title, 'John' Surname, 4 AddressCount",
(person, addressCount) =>
{
return person;
},
(person, addressCount) => person,
splitOn: "AddressCount"
).FirstOrDefault();
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册