File: ExpressionDispatcher.Registrar.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (602 lines) | stat: -rw-r--r-- 29,049 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
#region MIT license
// 
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// 
#endregion

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using DbLinq.Util;

using DbLinq.Data.Linq.Mapping;
using DbLinq.Data.Linq.Sugar;
using DbLinq.Data.Linq.Sugar.Expressions;

#if MONO_STRICT
using DataContext = System.Data.Linq.DataContext;
#else
using DataContext = DbLinq.Data.Linq.DataContext;
#endif

namespace DbLinq.Data.Linq.Sugar.Implementation
{
    internal partial class ExpressionDispatcher
    {

        /// <summary>
        /// Returns a registered column, or null if not found
        /// This method requires the table to be already registered
        /// </summary>
        /// <param name="table"></param>
        /// <param name="name"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected virtual ColumnExpression GetRegisteredColumn(TableExpression table, string name,
                                                               BuilderContext builderContext)
        {
            return
                (from queryColumn in builderContext.EnumerateScopeColumns()
                 where queryColumn.Table.IsEqualTo(table) && queryColumn.Name == name
                 select queryColumn).SingleOrDefault();
        }

        /// <summary>
        /// Returns an existing table or registers the current one
        /// </summary>
        /// <param name="tableExpression"></param>
        /// <param name="builderContext"></param>
        /// <returns>A registered table or the current newly registered one</returns>
        public virtual TableExpression RegisterTable(TableExpression tableExpression, BuilderContext builderContext)
        {
            // 1. Find the table in current scope
            var foundTableExpression = (from t in builderContext.EnumerateScopeTables()
                                        where t.IsEqualTo(tableExpression)
                                        select t).SingleOrDefault();
            if (foundTableExpression != null)
                return foundTableExpression;
            // 2. Find it in all scopes, and promote it to current scope.
            foundTableExpression = PromoteTable(tableExpression, builderContext);
            if (foundTableExpression != null)
                return foundTableExpression;
            // 3. Add it
            builderContext.CurrentSelect.Tables.Add(tableExpression);
            return tableExpression;
        }

        /// <summary>
        /// Promotes a table to a common parent between its current scope and our current scope
        /// </summary>
        /// <param name="tableExpression"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected virtual TableExpression PromoteTable(TableExpression tableExpression, BuilderContext builderContext)
        {
            int currentIndex = 0;
            SelectExpression oldSelect = null;
            SelectExpression commonScope = null;
            TableExpression foundTable = null;
            do
            {
                // take a select
                oldSelect = builderContext.SelectExpressions[currentIndex];

                // look for a common scope
                if (oldSelect != builderContext.CurrentSelect)
                {
                    commonScope = FindCommonScope(oldSelect, builderContext.CurrentSelect);
                    if (commonScope != null)
                        // if a common scope exists, look for an equivalent table in that select
                        for (int tableIndex = 0; tableIndex < oldSelect.Tables.Count && foundTable == null; tableIndex++)
                        {
                            if (oldSelect.Tables[tableIndex].IsEqualTo(tableExpression))
                            {
                                // found a matching table!
                                foundTable = oldSelect.Tables[tableIndex];
                            }
                        }
                }
                ++currentIndex;
            }
            while (currentIndex < builderContext.SelectExpressions.Count && foundTable == null);

            if (foundTable != null)
            {
                oldSelect.Tables.Remove(foundTable);
                commonScope.Tables.Add(foundTable);
            }
            return foundTable;
        }

        /// <summary>
        /// Find the common ancestor between two ScopeExpressions
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        protected virtual SelectExpression FindCommonScope(SelectExpression a, SelectExpression b)
        {
            for (var aScope = a; aScope != null; aScope = aScope.Parent)
            {
                for (var bScope = b; bScope != null; bScope = bScope.Parent)
                {
                    if (aScope == bScope)
                        return aScope;
                }
            }
            return null;
        }

        /// <summary>
        /// Registers a column
        /// This method requires the table to be already registered
        /// </summary>
        /// <param name="table"></param>
        /// <param name="memberInfo"></param>
        /// <param name="name"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public ColumnExpression RegisterColumn(TableExpression table,
                                               MemberInfo memberInfo, string name,
                                               BuilderContext builderContext)
        {
            if (memberInfo == null)
                return null;
            var queryColumn = GetRegisteredColumn(table, name, builderContext);
            if (queryColumn == null)
            {
                table = RegisterTable(table, builderContext);
                queryColumn = CreateColumn(table, memberInfo, builderContext);
                builderContext.CurrentSelect.Columns.Add(queryColumn);
            }
            return queryColumn;
        }

        /// <summary>
        /// Registers a column with only a table and a MemberInfo (this is the preferred method overload)
        /// </summary>
        /// <param name="tableExpression"></param>
        /// <param name="memberInfo"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public ColumnExpression RegisterColumn(TableExpression tableExpression, MemberInfo memberInfo,
                                               BuilderContext builderContext)
        {
            var dataMember = builderContext.QueryContext.DataContext.Mapping.GetTable(tableExpression.Type).RowType
                .GetDataMember(memberInfo);
            if (dataMember == null)
                return null;
            return RegisterColumn(tableExpression, memberInfo, dataMember.MappedName, builderContext);
        }

        public ColumnExpression CreateColumn(TableExpression table, MemberInfo memberInfo, BuilderContext builderContext)
        {
            var dataMember = builderContext.QueryContext.DataContext.Mapping.GetTable(table.Type).RowType
                .GetDataMember(memberInfo);
            if (dataMember == null)
                return null;
            return new ColumnExpression(table, dataMember);
        }

        /// <summary>
        /// Creates a default TableExpression
        /// </summary>
        /// <param name="tableType"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual TableExpression CreateTable(Type tableType, BuilderContext builderContext)
        {
            return new TableExpression(tableType, DataMapper.GetTableName(tableType, builderContext.QueryContext.DataContext));
        }

        /// <summary>
        /// Registers an association
        /// </summary>
        /// <param name="tableExpression">The table holding the member, to become the joinedTable</param>
        /// <param name="tableMemberInfo"></param>
        /// <param name="otherType"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual TableExpression RegisterAssociation(TableExpression tableExpression, MemberInfo tableMemberInfo,
                                                           Type otherType, BuilderContext builderContext)
        {
            IList<MemberInfo> otherKeys;
            TableJoinType joinType;
            string joinID;
            var theseKeys = DataMapper.GetAssociation(tableExpression, tableMemberInfo, otherType, out otherKeys,
                                                      out joinType, out joinID, builderContext.QueryContext.DataContext);
            // if the memberInfo has no corresponding association, we get a null, that we propagate
            if (theseKeys == null)
                return null;

            // the current table has the foreign key, the other table the referenced (usually primary) key
            if (theseKeys.Count != otherKeys.Count)
                throw Error.BadArgument("S0128: Association arguments (FK and ref'd PK) don't match");

            // we first create the table, with the JoinID, and we MUST complete the table later, with the Join() method
            var otherTableExpression = new TableExpression(otherType, DataMapper.GetTableName(otherType, builderContext.QueryContext.DataContext), joinID);

            Expression joinExpression = null;

            var createdColumns = new List<ColumnExpression>();
            for (int keyIndex = 0; keyIndex < theseKeys.Count; keyIndex++)
            {
                // joinedKey is registered, even if unused by final select (required columns will be filtered anyway)
                Expression otherKey = RegisterColumn(otherTableExpression, otherKeys[keyIndex], builderContext);
                // foreign is created, we will store it later if this assocation is registered too
                Expression thisKey = CreateColumn(tableExpression, theseKeys[keyIndex], builderContext);
                createdColumns.Add((ColumnExpression)thisKey);

                // if the key is nullable, then convert it
                // TODO: this will probably need to be changed
                if (otherKey.Type.IsNullable())
                    otherKey = Expression.Convert(otherKey, otherKey.Type.GetNullableType());
                if (thisKey.Type.IsNullable())
                    thisKey = Expression.Convert(thisKey, thisKey.Type.GetNullableType());
                // the other key is set as left operand, this must be this way
                // since some vendors (SQL Server) don't support the opposite
                var referenceExpression = Expression.Equal(otherKey, thisKey);

                // if we already have a join expression, then we have a double condition here, so "AND" it
                if (joinExpression != null)
                    joinExpression = Expression.And(joinExpression, referenceExpression);
                else
                    joinExpression = referenceExpression;
            }
            // we complete the table here, now that we have all join information
            otherTableExpression.Join(joinType, tableExpression, joinExpression);

            // our table is created, with the expressions
            // now check if we didn't register exactly the same
            var existingTable = (from t in builderContext.EnumerateScopeTables() where t.IsEqualTo(otherTableExpression) select t).SingleOrDefault();
            if (existingTable != null)
                return existingTable;
 
            builderContext.CurrentSelect.Tables.Add(otherTableExpression);
            foreach (var createdColumn in createdColumns)
                builderContext.CurrentSelect.Columns.Add(createdColumn);
            return otherTableExpression;
        }

        /// <summary>
        /// Registers an external parameter
        /// Since these can be complex expressions, we don't try to identify them
        /// and push them every time
        /// The only loss may be a small memory loss (if anyone can prove me that the same Expression can be used twice)
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="alias"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual InputParameterExpression RegisterParameter(Expression expression, string alias, BuilderContext builderContext)
        {
            var queryParameterExpression = new InputParameterExpression(expression, alias);
            builderContext.ExpressionQuery.Parameters.Add(queryParameterExpression);
            return queryParameterExpression;
        }

        public virtual void UnregisterParameter(InputParameterExpression expression, BuilderContext builderContext)
        {
            builderContext.ExpressionQuery.Parameters.Remove(expression);
        }

        /// <summary>
        /// Registers a MetaTable
        /// </summary>
        /// <param name="metaTableType"></param>
        /// <param name="aliases"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual MetaTableExpression RegisterMetaTable(Type metaTableType, IDictionary<MemberInfo, MutableExpression> aliases,
                                                             BuilderContext builderContext)
        {
            MetaTableExpression metaTableExpression;
            if (!builderContext.MetaTables.TryGetValue(metaTableType, out metaTableExpression))
            {
                metaTableExpression = new MetaTableExpression(aliases, metaTableType);
                builderContext.MetaTables[metaTableType] = metaTableExpression;
            }
            return metaTableExpression;
        }

        /// <summary>
        /// Registers a where clause in the current context scope
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <param name="builderContext"></param>
        public virtual void RegisterWhere(Expression whereExpression, BuilderContext builderContext)
        {
            builderContext.CurrentSelect.Where.Add(whereExpression);
        }

        /// <summary>
        /// Registers all columns of a table.
        /// </summary>
        /// <param name="tableExpression"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual IEnumerable<ColumnExpression> RegisterAllColumns(TableExpression tableExpression, BuilderContext builderContext)
        {
            foreach (var metaMember in builderContext.QueryContext.DataContext.Mapping.GetTable(tableExpression.Type).RowType.PersistentDataMembers)
            {
                yield return RegisterColumn(tableExpression, metaMember.Member, builderContext);
            }
        }

        /// <summary>
        /// Registers an expression to be returned by main request.
        /// The strategy is to try to find it in the already registered parameters, and if not found, add it
        /// </summary>
        /// <param name="expression">The expression to be registered</param>
        /// <param name="builderContext"></param>
        /// <returns>Expression index</returns>
        public virtual int RegisterOutputParameter(Expression expression, BuilderContext builderContext)
        {
            var scope = builderContext.CurrentSelect;
            var operands = scope.Operands.ToList();
            for (int index = 0; index < operands.Count; index++)
            {
                if (ExpressionEquals(operands[index], expression))
                    return index;
            }
            operands.Add(expression);
            builderContext.CurrentSelect = (SelectExpression)scope.Mutate(operands);
            return operands.Count - 1;
        }

        protected virtual bool ExpressionEquals(Expression a, Expression b)
        {
            // TODO: something smarter, to compare contents and not only references (works fine only for columns)
            return a == b;
        }

        /// <summary>
        /// Registers the table as returned by the SQL request.
        /// Actually, the table is split into its columns.
        /// </summary>
        /// <param name="tableExpression"></param>
        /// <param name="dataRecordParameter"></param>
        /// <param name="mappingContextParameter"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected virtual Expression GetOutputTableReader(TableExpression tableExpression,
                                                          ParameterExpression dataRecordParameter, ParameterExpression mappingContextParameter,
                                                          BuilderContext builderContext)
        {
            var bindings = new List<MemberBinding>();
            
            foreach (ColumnExpression columnExpression in RegisterAllColumns(tableExpression, builderContext))
            {
                MemberInfo memberInfo = columnExpression.StorageInfo ?? columnExpression.MemberInfo;
                PropertyInfo propertyInfo = memberInfo as PropertyInfo;
                if (propertyInfo == null || propertyInfo.CanWrite)
                {
                    var parameterColumn = GetOutputValueReader(columnExpression,
                                                               dataRecordParameter, mappingContextParameter, builderContext);
                    var binding = Expression.Bind(memberInfo, parameterColumn);
                    bindings.Add(binding);
                }
            }
            var newExpression = Expression.New(tableExpression.Type);
            var initExpression = Expression.MemberInit(newExpression, bindings);
            return initExpression;
        }

        /// <summary>
        /// Builds a Row builder, based on a given list of parameters
        /// </summary>
        /// <param name="tableType"></param>
        /// <param name="parameters"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual LambdaExpression BuildTableReader(Type tableType, IList<string> parameters, BuilderContext builderContext)
        {
            var dataRecordParameter = Expression.Parameter(typeof(IDataRecord), "dataRecord");
            var mappingContextParameter = Expression.Parameter(typeof(MappingContext), "mappingContext");
            //var table = builderContext.QueryContext.DataContext.Mapping.GetTable(tableType);
            var bindings = new List<MemberBinding>();
            for (int parameterIndex = 0; parameterIndex < parameters.Count; parameterIndex++)
            {
				var parameter = parameters[parameterIndex];
				var memberInfo = tableType.GetTableColumnMember(parameter);
                if (memberInfo == null)
                {
                    memberInfo = tableType.GetSingleMember(parameter, BindingFlags.Public | BindingFlags.NonPublic
                                                                      | BindingFlags.Instance | BindingFlags.IgnoreCase);
                }
                // TODO real error
                if (memberInfo == null)
                    throw new ArgumentException(string.Format("Invalid column '{0}'", parameter));
                //var column = DataMapper.GetColumnName(tableType, memberInfo, builderContext.QueryContext.DataContext);
                //var columnName = DataMapper.GetColumnName(tableType, memberInfo, builderContext.QueryContext.DataContext);
                var invoke = GetOutputValueReader(memberInfo.GetMemberType(), parameterIndex, //GetTableIndex(parameters, columnName),
                                                  dataRecordParameter, mappingContextParameter);
                var parameterColumn = GetOutputValueReader(invoke, dataRecordParameter, mappingContextParameter,
                                                           builderContext);
                var binding = Expression.Bind(memberInfo, parameterColumn);
                bindings.Add(binding);
            }
            var newExpression = Expression.New(tableType);
            var initExpression = Expression.MemberInit(newExpression, bindings);
            return Expression.Lambda(initExpression, dataRecordParameter, mappingContextParameter);
        }

        protected virtual int GetTableIndex(IList<string> parameters, string columnName)
        {
            int index = parameters.IndexOf(columnName);
            if (index >= 0)
                return index;
            for (index = 0; index < parameters.Count; index++)
            {
                if (string.Compare(parameters[index], columnName, true) == 0)
                {
                    return index;
                }
            }
            return -1;
        }

        /// <summary>
        /// Creates an entity set creator, to be used at run-time
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="dataRecordParameter"></param>
        /// <param name="mappingContextParameter"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected virtual Expression GetEntitySetBuilder(EntitySetExpression expression,
                                                          ParameterExpression dataRecordParameter, ParameterExpression mappingContextParameter,
                                                          BuilderContext builderContext)
        {
            var entityType = expression.EntitySetType.GetGenericArguments()[0];
            List<ElementInit> members = new List<ElementInit>();
            var add = expression.EntitySetType.GetMethod("Add", 
                    BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    new Type[] { typeof(KeyValuePair<object, MemberInfo>) },
                    null);

            foreach (var info in expression.Columns)
            {
                var column = info.Key;
                var tk = info.Value;
                MemberInfo memberInfo = column.StorageInfo ?? column.MemberInfo;
                PropertyInfo propertyInfo = memberInfo as PropertyInfo;
                if (propertyInfo == null || propertyInfo.CanWrite)
                {
                    var parameterColumn = GetOutputValueReader(column,
                            dataRecordParameter, mappingContextParameter, builderContext);
                    members.Add(Expression.ElementInit(add, 
                            new Expression[]{
                                Expression.New(typeof(KeyValuePair<object, MemberInfo>).GetConstructor(new Type[]{typeof(object), typeof(MemberInfo)}),
                                    Expression.Convert(parameterColumn, typeof(object)), 
                                    Expression.Constant(tk.Member, typeof(MemberInfo)))}));
                }
            }

            return Expression.ListInit(
                    Expression.New(
                        expression.EntitySetType.GetConstructor(
                            BindingFlags.NonPublic | BindingFlags.Instance,
                            null,
                            new[] { typeof(DataContext) },
                            null),
                        Expression.Constant(builderContext.QueryContext.DataContext)),
                    members);
        }

        /// <summary>
        /// Registers the expression as returned by the SQL request.
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="dataRecordParameter"></param>
        /// <param name="mappingContextParameter"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected virtual Expression GetOutputValueReader(Expression expression,
                                                          ParameterExpression dataRecordParameter, ParameterExpression mappingContextParameter,
                                                          BuilderContext builderContext)
        {
            int valueIndex = RegisterOutputParameter(expression, builderContext);
            return GetOutputValueReader(expression.Type, valueIndex, dataRecordParameter, mappingContextParameter);
        }

        /// <summary>
        /// Registers the ColumnExpression as returned by the SQL request.
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="dataRecordParameter"></param>
        /// <param name="mappingContextParameter"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected virtual Expression GetOutputValueReader(ColumnExpression expression,
                                                          ParameterExpression dataRecordParameter, ParameterExpression mappingContextParameter,
                                                          BuilderContext builderContext)
        {
            int valueIndex = RegisterOutputParameter(expression, builderContext);
            Type storageType = expression.StorageInfo != null ? expression.StorageInfo.GetMemberType() : null;
            return GetOutputValueReader(storageType ?? expression.Type, valueIndex, dataRecordParameter, mappingContextParameter);
        }


        /// <summary>
        /// Registers the expression as returned column
        /// </summary>
        /// <param name="columnType"></param>
        /// <param name="valueIndex"></param>
        /// <param name="dataRecordParameter"></param>
        /// <param name="mappingContextParameter"></param>
        /// <returns></returns>
        protected virtual Expression GetOutputValueReader(Type columnType, int valueIndex, ParameterExpression dataRecordParameter,
                                                          ParameterExpression mappingContextParameter)
        {
            var propertyReaderLambda = DataRecordReader.GetPropertyReader(columnType);
            Expression invoke = new ParameterBinder().BindParams(propertyReaderLambda,
                dataRecordParameter, mappingContextParameter, Expression.Constant(valueIndex));
            if (!columnType.IsNullable())
                invoke = Expression.Convert(invoke, columnType);
            return invoke;
        }
    }

    class ParameterBinder
    {
        Dictionary<Expression, Expression> map;

        public Expression BindParams(LambdaExpression expr, params Expression[] args)
        {
            map = new Dictionary<Expression, Expression>();

            if (expr.Parameters.Count != args.Length)
                throw new NotImplementedException();
            for (int i = 0; i < expr.Parameters.Count; ++i)
                map[expr.Parameters[i]] = args[i];
            return Visit(expr.Body);
        }

        Expression Visit(Expression expr)
        {
            switch (expr.NodeType)
            {
                case ExpressionType.Call:
                    MethodCallExpression call = expr as MethodCallExpression;
                    Expression[] new_args = new Expression[call.Arguments.Count];
                    for (int i = 0; i < new_args.Length; ++i)
                        new_args[i] = Visit(call.Arguments[i]);
                    return Expression.Call(call.Object, call.Method, new_args);
                case ExpressionType.Parameter:
                    Expression new_expr;
                    if (map.TryGetValue(expr, out new_expr))
                        return new_expr;
                    break;
                default:
                    throw new Exception("Can't handle " + expr.NodeType);
            }

            return expr;
        }
    }
}