|
9 | 9 |
|
10 | 10 | namespace Simple.Data.Ado |
11 | 11 | { |
| 12 | + using System.Data.SqlClient; |
| 13 | + using System.Dynamic; |
| 14 | + |
12 | 15 | class AdoAdapterFinder |
13 | 16 | { |
14 | 17 | private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, CommandTemplate>> _commandCaches = |
@@ -47,8 +50,34 @@ public Func<object[],IDictionary<string,object>> CreateFindOneDelegate(string ta |
47 | 50 | { |
48 | 51 | return _ => FindAll(_adapter.GetSchema().BuildObjectName(tableName)).FirstOrDefault(); |
49 | 52 | } |
50 | | - var commandTemplate = GetCommandTemplate(tableName, criteria); |
51 | | - return args => ExecuteSingletonQuery(commandTemplate, args); |
| 53 | + var commandBuilder = new FindHelper(_adapter.GetSchema()) |
| 54 | + .GetFindByCommand(_adapter.GetSchema().BuildObjectName(tableName), criteria); |
| 55 | + |
| 56 | + var command = commandBuilder.GetCommand(_adapter.CreateConnection()); |
| 57 | + |
| 58 | + var commandTemplate = |
| 59 | + commandBuilder.GetCommandTemplate( |
| 60 | + _adapter.GetSchema().FindTable(_adapter.GetSchema().BuildObjectName(tableName))); |
| 61 | + |
| 62 | + var cloneable = command as ICloneable; |
| 63 | + if (cloneable != null) |
| 64 | + { |
| 65 | + return args => ExecuteSingletonQuery((IDbCommand)cloneable.Clone(), args, commandTemplate.Index); |
| 66 | + } |
| 67 | + else |
| 68 | + { |
| 69 | + return args => ExecuteSingletonQuery(commandTemplate, args); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + private IDictionary<string, object> ExecuteSingletonQuery(IDbCommand command, object[] parameterValues, IDictionary<string,int> index) |
| 74 | + { |
| 75 | + for (int i = 0; i < command.Parameters.Count; i++) |
| 76 | + { |
| 77 | + ((IDbDataParameter) command.Parameters[i]).Value = FixObjectType(parameterValues[i]); |
| 78 | + } |
| 79 | + command.Connection = _adapter.CreateConnection(); |
| 80 | + return TryExecuteSingletonQuery(command.Connection, command, index); |
52 | 81 | } |
53 | 82 |
|
54 | 83 | public IEnumerable<IDictionary<string, object>> Find(string tableName, SimpleExpression criteria) |
@@ -149,5 +178,17 @@ private static IDictionary<string, object> TryExecuteSingletonQuery(IDbConnectio |
149 | 178 | } |
150 | 179 | return null; |
151 | 180 | } |
| 181 | + |
| 182 | + private static object FixObjectType(object value) |
| 183 | + { |
| 184 | + if (value == null) return DBNull.Value; |
| 185 | + if (TypeHelper.IsKnownType(value.GetType())) return value; |
| 186 | + var dynamicObject = value as DynamicObject; |
| 187 | + if (dynamicObject != null) |
| 188 | + { |
| 189 | + return dynamicObject.ToString(); |
| 190 | + } |
| 191 | + return value; |
| 192 | + } |
152 | 193 | } |
153 | 194 | } |
0 commit comments