-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLinqToSqlExtensions.cs
1289 lines (1089 loc) · 69 KB
/
LinqToSqlExtensions.cs
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright(c) 2015 Terry Aney
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.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
namespace BTR.Core.Linq
{
[System.Diagnostics.CodeAnalysis.SuppressMessage( "BTR.Globalization", "MH1000:StringLiteralsShouldBeInResxOrIgnored", Justification = "Code, not text.", Target="*:MH1000:StringLiteralsShouldBeInResxOrIgnored" )]
public static class LinqToSqlExtensions
{
/// <summary>
/// Creates a *.csv file from an IQueryable query, dumping out the 'simple' properties/fields.
/// </summary>
/// <param name="query">Represents a SELECT query to execute.</param>
/// <param name="fileName">The name of the file to create.</param>
/// <remarks>
/// <para>If the file specified by <paramref name="fileName"/> exists, it will be deleted.</para>
/// <para>If the <paramref name="query"/> contains any properties that are entity sets (i.e. rows from a FK relationship) the values will not be dumped to the file.</para>
/// <para>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</para>
/// </remarks>
public static T DumpCSV<T>( this T query, string fileName ) where T : System.Collections.IEnumerable
{
return query.DumpCSV( fileName, true, null );
}
/// <summary>
/// Creates a *.csv file from an IQueryable query, dumping out the 'simple' properties/fields.
/// </summary>
/// <param name="query">Represents a SELECT query to execute.</param>
/// <param name="fileName">The name of the file to create.</param>
/// <param name="deleteFile">Whether or not to delete the file specified by <paramref name="fileName"/> if it exists.</param>
/// <param name="translateValue">A call back function used to translate the value if the raw value needs to be massaged.</param>
/// <remarks>
/// <para>If the <paramref name="query"/> contains any properties that are entity sets (i.e. rows from a FK relationship) the values will not be dumped to the file.</para>
/// <para>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</para>
/// </remarks>
public static T DumpCSV<T>( this T query, string fileName, bool deleteFile, Func<MemberInfo, object, object> translateValue = null ) where T : System.Collections.IEnumerable
{
if ( File.Exists( fileName ) && deleteFile )
{
File.Delete( fileName );
}
using ( var output = new FileStream( fileName, FileMode.CreateNew ) )
{
return query.DumpCSV( output, translateValue );
}
}
public static T DumpCSV<T>( this T query, Stream stream, string delimitter = ",", Encoding encoding = null ) where T : System.Collections.IEnumerable
{
return query.DumpCSV( stream, null, delimitter, encoding );
}
private static T DumpCSV<T>( this T query, Stream stream, Func<MemberInfo, object, object> translateValue = null, string delimitter = ",", Encoding encoding = null ) where T : System.Collections.IEnumerable
{
using ( var writer = new StreamWriter( stream, encoding ?? new UTF8Encoding( false, true ) ) )
{
var firstRow = true;
PropertyInfo[] properties = null;
FieldInfo[] fields = null;
Type type = null;
bool typeIsAnonymous = false;
foreach ( var r in query )
{
if ( type == null )
{
type = r.GetType();
typeIsAnonymous = type.IsAnonymous();
properties = type.GetProperties().Where( p => IsCsvExportAllowed( p.PropertyType, (MemberInfo)p ) ).ToArray();
fields = type.GetFields().Where( p => IsCsvExportAllowed( p.FieldType, (MemberInfo)p ) ).ToArray();
}
var firstCol = true;
if ( firstRow )
{
foreach ( var p in properties )
{
if ( !firstCol ) writer.Write( delimitter );
else { firstCol = false; }
writer.Write( CsvHeaderName( (MemberInfo)p ) );
}
foreach ( var p in fields )
{
if ( !firstCol ) writer.Write( delimitter );
else { firstCol = false; }
writer.Write( CsvHeaderName( (MemberInfo)p ) );
}
writer.WriteLine();
}
firstRow = false;
firstCol = true;
foreach ( var p in properties )
{
if ( !firstCol ) writer.Write( delimitter );
else { firstCol = false; }
var value = translateValue != null
? translateValue( p, r )
: p.GetValue( r, null );
DumpValue( value, writer, delimitter );
}
foreach ( var p in fields )
{
if ( !firstCol ) writer.Write( delimitter );
else { firstCol = false; }
var value = translateValue != null
? translateValue( p, r )
: p.GetValue( r );
DumpValue( value, writer, delimitter );
}
writer.WriteLine();
}
}
return query;
}
/// <summary>
/// Returns all fields/properties from <paramref name="source"/> except for the field(s)/property(ies) listed in the selector expression.
/// </summary>
public static IQueryable SelectExcept<TSource, TResult>( this IEnumerable<TSource> source, Expression<Func<TSource, TResult>> selector )
{
var newExpression = selector.Body as NewExpression;
var excludeProperties = newExpression != null
? newExpression.Members.Select( m => m.Name )
: new[] { ( (MemberExpression)selector.Body ).Member.Name };
var sourceType = typeof( TSource );
var allowedSelectTypes = new Type[] { typeof( string ), typeof( ValueType ), typeof( XElement ) };
var sourceProperties = sourceType.GetProperties( BindingFlags.Public | BindingFlags.Instance ).Where( p => allowedSelectTypes.Any( t => t.IsAssignableFrom( ( (PropertyInfo)p ).PropertyType ) ) ).Select( p => ( (MemberInfo)p ).Name );
var sourceFields = sourceType.GetFields( BindingFlags.Public | BindingFlags.Instance ).Where( f => allowedSelectTypes.Any( t => t.IsAssignableFrom( ( (FieldInfo)f ).FieldType ) ) ).Select( f => ( (MemberInfo)f ).Name );
var selectFields = sourceProperties.Concat( sourceFields ).Where( p => !excludeProperties.Contains( p ) ).ToArray();
var dynamicSelect =
string.Format( "new( {0} )",
string.Join( ", ", selectFields ) );
return selectFields.Count() > 0
? source.AsQueryable().Select( dynamicSelect )
: Enumerable.Empty<TSource>().AsQueryable<TSource>();
}
private static bool IsCsvExportAllowed( Type memberType, MemberInfo member )
{
var allowedCsvTypes = new Type[] { typeof( string ), typeof( ValueType ) };
if ( !allowedCsvTypes.Any( t => t.IsAssignableFrom( memberType ) ) ) return false;
var scaffoldColumnAttrib = member.GetCustomAttributes( typeof( ScaffoldColumnAttribute ), true ).Cast<ScaffoldColumnAttribute>().FirstOrDefault();
// BTR Tahiti attribute.
var xmlPropertyMappingAttr = member.GetCustomAttributes( true ).Cast<Attribute>().Where( a => a.GetType().Name == "XmlPropertyMappingAttribute" ).FirstOrDefault();
return scaffoldColumnAttrib == null || scaffoldColumnAttrib.Scaffold || xmlPropertyMappingAttr != null;
}
/// <summary>
/// Gets the header name. Didn't directly reference BTR's Tahiti assemblies, but instead did late binding/reflection to determine if there.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
private static string CsvHeaderName( MemberInfo member )
{
var attributes = member.GetCustomAttributes( true ).Cast<Attribute>();
var exportNameAttr = attributes.Where( a => a.GetType().Name == "ExportNameAttribute" ).FirstOrDefault();
var xmlPropertyMappingAttr = attributes.Where( a => a.GetType().Name == "XmlPropertyMappingAttribute" ).FirstOrDefault();
var displayAttr = attributes.Where( a => a.GetType().Name == "DisplayAttribute" ).FirstOrDefault();
var authIdAttr = attributes.Where( a => a.GetType().Name == "AuthIdAttribute" ).FirstOrDefault();
var name = exportNameAttr != null
? (string)exportNameAttr.GetType().GetProperty( "Name" ).GetValue( exportNameAttr, null )
: xmlPropertyMappingAttr != null
? (string)xmlPropertyMappingAttr.GetType().GetProperty( "XmlField" ).GetValue( xmlPropertyMappingAttr, null )
: displayAttr != null
? (string)displayAttr.GetType().GetMethod( "GetName" ).Invoke( displayAttr, null )
: member.Name;
return authIdAttr != null ? name + "/key" : name;
}
private static void DumpValue( object v, StreamWriter writer, string delimitter )
{
if ( v != null )
{
switch ( Type.GetTypeCode( v.GetType() ) )
{
// csv encode the value
case TypeCode.String:
string value = (string)v;
if ( value.Contains( delimitter ) || value.Contains( '"' ) || value.Contains( "\n" ) )
{
value = value.Replace( "\"", "\"\"" );
if ( value.Length > 31735 )
{
value = value.Substring( 0, 31732 ) + "...";
}
writer.Write( "\"" + value + "\"" );
}
else
{
writer.Write( value );
}
break;
default: writer.Write( v ); break;
}
}
}
public static bool IsAnonymous( this Type type )
{
if ( type == null )
throw new ArgumentNullException( "type" );
// HACK: The only way to detect anonymous types right now.
return Attribute.IsDefined( type, typeof( CompilerGeneratedAttribute ), false )
&& type.IsGenericType && type.Name.Contains( "AnonymousType" )
&& ( type.Name.StartsWith( "<>" ) || type.Name.StartsWith( "VB$" ) )
&& ( type.Attributes & TypeAttributes.NotPublic ) == TypeAttributes.NotPublic;
}
/// <summary>
/// Batches together multiple IQueryable queries into a single DbCommand and returns all data in
/// a single roundtrip to the database.
/// </summary>
/// <param name="context">The DataContext to execute the batch select against.</param>
/// <param name="queries">Represents a collections of SELECT queries to execute.</param>
/// <returns>Returns an IMultipleResults object containing all results.</returns>
public static IMultipleResults SelectMutlipleResults( this DataContext context, IQueryable[] queries )
{
var commandList = new List<DbCommand>();
foreach ( IQueryable query in queries )
{
var command = context.GetCommand( query );
commandList.Add( command );
}
SqlCommand batchCommand = CombineCommands( commandList );
batchCommand.Connection = context.Connection as SqlConnection;
DbDataReader dr = null;
if ( batchCommand.Connection.State == ConnectionState.Closed )
{
batchCommand.Connection.Open();
dr = batchCommand.ExecuteReader( CommandBehavior.CloseConnection );
}
else
{
dr = batchCommand.ExecuteReader();
}
IMultipleResults mr = context.Translate( dr );
return mr;
}
/// <summary>
/// Combines multiple SELECT commands into a single SqlCommand so that all statements can be executed in a
/// single roundtrip to the database and return multiple result sets.
/// </summary>
/// <param name="commandList">Represents a collection of commands to be batched together.</param>
/// <returns>Returns a single SqlCommand that executes all SELECT statements at once.</returns>
private static SqlCommand CombineCommands( List<DbCommand> selectCommands )
{
SqlCommand batchCommand = new SqlCommand();
SqlParameterCollection newParamList = batchCommand.Parameters;
int commandCount = 0;
foreach ( DbCommand cmd in selectCommands )
{
string commandText = cmd.CommandText;
DbParameterCollection paramList = cmd.Parameters;
int paramCount = paramList.Count;
for ( int currentParam = paramCount - 1; currentParam >= 0; currentParam-- )
{
DbParameter param = paramList[ currentParam ];
DbParameter newParam = CloneParameter( param );
string newParamName = param.ParameterName.Replace( "@", string.Format( "@{0}_", commandCount ) );
commandText = commandText.Replace( param.ParameterName, newParamName );
newParam.ParameterName = newParamName;
newParamList.Add( newParam );
}
if ( batchCommand.CommandText.Length > 0 )
{
batchCommand.CommandText += ";";
}
batchCommand.CommandText += commandText;
commandCount++;
}
return batchCommand;
}
/// <summary>
/// Returns a clone (via copying all properties) of an existing DbParameter.
/// </summary>
/// <param name="src">The DbParameter to clone.</param>
/// <returns>Returns a clone (via copying all properties) of an existing DbParameter.</returns>
private static DbParameter CloneParameter( DbParameter src )
{
SqlParameter source = (SqlParameter)src;
SqlParameter destination = new SqlParameter();
destination.Value = source.Value;
destination.Direction = source.Direction;
destination.Size = source.Size;
destination.Offset = source.Offset;
destination.SourceColumn = source.SourceColumn;
destination.SourceVersion = source.SourceVersion;
destination.SourceColumnNullMapping = source.SourceColumnNullMapping;
destination.IsNullable = source.IsNullable;
destination.CompareInfo = source.CompareInfo;
destination.XmlSchemaCollectionDatabase = source.XmlSchemaCollectionDatabase;
destination.XmlSchemaCollectionOwningSchema = source.XmlSchemaCollectionOwningSchema;
destination.XmlSchemaCollectionName = source.XmlSchemaCollectionName;
destination.UdtTypeName = source.UdtTypeName;
destination.TypeName = source.TypeName;
destination.ParameterName = source.ParameterName;
destination.Precision = source.Precision;
destination.Scale = source.Scale;
return destination;
}
/// <summary>
/// Immediately deletes all entities from the collection with a single delete command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be deleted.</param>
/// <typeparam name="TPrimaryKey">Represents the object type for the primary key of rows contained in <paramref name="table"/>.</typeparam>
/// <param name="primaryKey">Represents the primary key of the item to be removed from <paramref name="table"/>.</param>
/// <returns>The number of rows deleted from the database (maximum of 1).</returns>
/// <remarks>
/// <para>If the primary key for <paramref name="table"/> is a composite key, <paramref name="primaryKey"/> should be an anonymous type with property names mapping to the property names of objects of type <typeparamref name="TEntity"/>.</para>
/// </remarks>
public static int DeleteByPK<TEntity>( this Table<TEntity> table, object primaryKey ) where TEntity : class
{
DbCommand delete = table.GetDeleteByPKCommand<TEntity>( primaryKey );
var parameters = from p in delete.Parameters.Cast<DbParameter>()
select p.Value;
return table.Context.ExecuteCommand( delete.CommandText, parameters.ToArray() );
}
/// <summary>Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete a entity row via the supplied primary key.</summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be deleted.</param>
/// <typeparam name="TPrimaryKey">Represents the object type for the primary key of rows contained in <paramref name="table"/>.</typeparam>
/// <param name="primaryKey">Represents the primary key of the item to be removed from <paramref name="table"/>.</param>
/// <returns>Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete a entity row via the supplied primary key.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
public static string DeleteByPKPreview<TEntity>( this Table<TEntity> table, object primaryKey ) where TEntity : class
{
DbCommand delete = table.GetDeleteByPKCommand<TEntity>( primaryKey );
return delete.PreviewCommandText( false ) + table.Context.GetLog();
}
private static DbCommand GetDeleteByPKCommand<TEntity>( this Table<TEntity> table, object primaryKey ) where TEntity : class
{
Type type = primaryKey.GetType();
bool typeIsAnonymous = type.IsAnonymous();
string dbName = table.GetDbName();
var metaTable = table.Context.Mapping.GetTable( typeof( TEntity ) );
var keys = from mdm in metaTable.RowType.DataMembers
where mdm.IsPrimaryKey
select new { mdm.MappedName, mdm.Name, mdm.Type };
SqlCommand deleteCommand = new SqlCommand();
deleteCommand.Connection = table.Context.Connection as SqlConnection;
var whereSB = new StringBuilder();
foreach ( var key in keys )
{
// Add new parameter with massaged name to avoid clashes.
whereSB.AppendFormat( "[{0}] = @p{1}, ", key.MappedName, deleteCommand.Parameters.Count );
object value = primaryKey;
if ( typeIsAnonymous || ( type.IsClass && type != typeof( string ) ) )
{
if ( typeIsAnonymous )
{
PropertyInfo property = type.GetProperty( key.Name );
if ( property == null )
{
throw new ArgumentOutOfRangeException( string.Format( "The property {0} which is defined as part of the primary key for {1} was not supplied by the parameter primaryKey.", key.Name, metaTable.TableName ) );
}
value = property.GetValue( primaryKey, null );
}
else
{
FieldInfo field = type.GetField( key.Name );
if ( field == null )
{
throw new ArgumentOutOfRangeException( string.Format( "The property {0} which is defined as part of the primary key for {1} was not supplied by the parameter primaryKey.", key.Name, metaTable.TableName ) );
}
value = field.GetValue( primaryKey );
}
if ( value.GetType() != key.Type )
{
throw new InvalidCastException( string.Format( "The property {0} ({1}) does not have the same type as {2} ({3}).", key.Name, value.GetType(), key.MappedName, key.Type ) );
}
}
else if ( value.GetType() != key.Type )
{
throw new InvalidCastException( string.Format( "The value supplied in primaryKey ({0}) does not have the same type as {1} ({2}).", value.GetType(), key.MappedName, key.Type ) );
}
deleteCommand.Parameters.Add( new SqlParameter( string.Format( "@p{0}", deleteCommand.Parameters.Count ), value ) );
}
string wherePK = whereSB.ToString();
if ( wherePK == "" )
{
throw new MissingPrimaryKeyException( string.Format( "{0} does not have a primary key defined. Batch updating/deleting can not be used for tables without a primary key.", metaTable.TableName ) );
}
deleteCommand.CommandText = string.Format( "DELETE {0}\r\nWHERE {1}", dbName, wherePK.Substring( 0, wherePK.Length - 2 ) );
return deleteCommand;
}
/// <summary>
/// Immediately deletes all entities from the collection with a single delete command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be deleted.</param>
/// <param name="entities">Represents the collection of items which are to be removed from <paramref name="table"/>.</param>
/// <returns>The number of rows deleted from the database.</returns>
/// <remarks>
/// <para>Similiar to stored procedures, and opposite from DeleteAllOnSubmit, rows provided in <paramref name="entities"/> will be deleted immediately with no need to call <see cref="DataContext.SubmitChanges()"/>.</para>
/// <para>Additionally, to improve performance, instead of creating a delete command for each item in <paramref name="entities"/>, a single delete command is created.</para>
/// </remarks>
public static int DeleteBatch<TEntity>( this Table<TEntity> table, IQueryable<TEntity> entities ) where TEntity : class
{
DbCommand delete = table.GetDeleteBatchCommand<TEntity>( entities );
var parameters = from p in delete.Parameters.Cast<DbParameter>()
select p.Value;
return table.Context.ExecuteCommand( delete.CommandText, parameters.ToArray() );
}
/// <summary>
/// Immediately deletes all entities from the collection with a single delete command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be deleted.</param>
/// <param name="filter">Represents a filter of items to be updated in <paramref name="table"/>.</param>
/// <returns>The number of rows deleted from the database.</returns>
/// <remarks>
/// <para>Similiar to stored procedures, and opposite from DeleteAllOnSubmit, rows provided in <paramref name="entities"/> will be deleted immediately with no need to call <see cref="DataContext.SubmitChanges()"/>.</para>
/// <para>Additionally, to improve performance, instead of creating a delete command for each item in <paramref name="entities"/>, a single delete command is created.</para>
/// </remarks>
public static int DeleteBatch<TEntity>( this Table<TEntity> table, Expression<Func<TEntity, bool>> filter ) where TEntity : class
{
return table.DeleteBatch( table.Where( filter ) );
}
/// <summary>
/// Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete all entities from the collection with a single delete command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be deleted.</param>
/// <param name="entities">Represents the collection of items which are to be removed from <paramref name="table"/>.</param>
/// <returns>Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete all entities from the collection with a single delete command.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
public static string DeleteBatchPreview<TEntity>( this Table<TEntity> table, IQueryable<TEntity> entities ) where TEntity : class
{
DbCommand delete = table.GetDeleteBatchCommand<TEntity>( entities );
return "Total Rows To Be Deleted By Query: " + entities.Count() + "\n\n" + delete.PreviewCommandText( false ) + table.Context.GetLog();
}
/// <summary>
/// Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete all entities from the collection with a single delete command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be deleted.</param>
/// <param name="filter">Represents a filter of items to be updated in <paramref name="table"/>.</param>
/// <returns>Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete all entities from the collection with a single delete command.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
public static string DeleteBatchPreview<TEntity>( this Table<TEntity> table, Expression<Func<TEntity, bool>> filter ) where TEntity : class
{
return table.DeleteBatchPreview( table.Where( filter ) );
}
/// <summary>
/// Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete all entities from the collection with a single delete command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be deleted.</param>
/// <param name="entities">Represents the collection of items which are to be removed from <paramref name="table"/>.</param>
/// <returns>Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete all entities from the collection with a single delete command.</returns>
/// <remarks>This method is useful for debugging purposes or when LINQ generated queries need to be passed to developers without LINQ/LINQPad.</remarks>
public static string DeleteBatchSQL<TEntity>( this Table<TEntity> table, IQueryable<TEntity> entities ) where TEntity : class
{
DbCommand delete = table.GetDeleteBatchCommand<TEntity>( entities );
return delete.PreviewCommandText( true );
}
/// <summary>
/// Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete all entities from the collection with a single delete command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be deleted.</param>
/// <param name="filter">Represents a filter of items to be updated in <paramref name="table"/>.</param>
/// <returns>Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to delete all entities from the collection with a single delete command.</returns>
/// <remarks>This method is useful for debugging purposes or when LINQ generated queries need to be passed to developers without LINQ/LINQPad.</remarks>
public static string DeleteBatchSQL<TEntity>( this Table<TEntity> table, Expression<Func<TEntity, bool>> filter ) where TEntity : class
{
return table.DeleteBatchSQL( table.Where( filter ) );
}
/// <summary>
/// Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to update all entities from the collection with a single update command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be updated.</param>
/// <param name="entities">Represents the collection of items which are to be updated in <paramref name="table"/>.</param>
/// <param name="evaluator">A Lambda expression returning a <typeparamref name="TEntity"/> that defines the update assignments to be performed on each item in <paramref name="entities"/>.</param>
/// <returns>Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to update all entities from the collection with a single update command.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
public static string UpdateBatchPreview<TEntity>( this Table<TEntity> table, IQueryable<TEntity> entities, Expression<Func<TEntity, TEntity>> evaluator ) where TEntity : class
{
DbCommand update = table.GetUpdateBatchCommand<TEntity>( entities, evaluator );
return "Total Rows To Be Updated By Query: " + entities.Count() + "\n\n" + update.PreviewCommandText( false ) + table.Context.GetLog();
}
/// <summary>
/// Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to update all entities from the collection with a single update command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be updated.</param>
/// <param name="filter">Represents a filter of items to be updated in <paramref name="table"/>.</param>
/// <param name="evaluator">A Lambda expression returning a <typeparamref name="TEntity"/> that defines the update assignments to be performed on each item in <paramref name="entities"/>.</param>
/// <returns>Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to update all entities from the collection with a single update command.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
public static string UpdateBatchPreview<TEntity>( this Table<TEntity> table, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TEntity>> evaluator ) where TEntity : class
{
return table.UpdateBatchPreview( table.Where( filter ), evaluator );
}
/// <summary>
/// Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to update all entities from the collection with a single update command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be updated.</param>
/// <param name="entities">Represents the collection of items which are to be updated in <paramref name="table"/>.</param>
/// <param name="evaluator">A Lambda expression returning a <typeparamref name="TEntity"/> that defines the update assignments to be performed on each item in <paramref name="entities"/>.</param>
/// <returns>Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to update all entities from the collection with a single update command.</returns>
/// <remarks>This method is useful for debugging purposes or when LINQ generated queries need to be passed to developers without LINQ/LINQPad.</remarks>
public static string UpdateBatchSQL<TEntity>( this Table<TEntity> table, IQueryable<TEntity> entities, Expression<Func<TEntity, TEntity>> evaluator ) where TEntity : class
{
DbCommand update = table.GetUpdateBatchCommand<TEntity>( entities, evaluator );
return update.PreviewCommandText( true );
}
/// <summary>
/// Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to update all entities from the collection with a single update command.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be updated.</param>
/// <param name="filter">Represents a filter of items to be updated in <paramref name="table"/>.</param>
/// <param name="evaluator">A Lambda expression returning a <typeparamref name="TEntity"/> that defines the update assignments to be performed on each item in <paramref name="entities"/>.</param>
/// <returns>Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to update all entities from the collection with a single update command.</returns>
/// <remarks>This method is useful for debugging purposes or when LINQ generated queries need to be passed to developers without LINQ/LINQPad.</remarks>
public static string UpdateBatchSQL<TEntity>( this Table<TEntity> table, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TEntity>> evaluator ) where TEntity : class
{
return table.UpdateBatchSQL( table.Where( filter ), evaluator );
}
/// <summary>
/// Immediately updates all entities in the collection with a single update command based on a <typeparamref name="TEntity"/> created from a Lambda expression.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be updated.</param>
/// <param name="entities">Represents the collection of items which are to be updated in <paramref name="table"/>.</param>
/// <param name="evaluator">A Lambda expression returning a <typeparamref name="TEntity"/> that defines the update assignments to be performed on each item in <paramref name="entities"/>.</param>
/// <returns>The number of rows updated in the database.</returns>
/// <remarks>
/// <para>Similiar to stored procedures, and opposite from similiar InsertAllOnSubmit, rows provided in <paramref name="entities"/> will be updated immediately with no need to call <see cref="DataContext.SubmitChanges()"/>.</para>
/// <para>Additionally, to improve performance, instead of creating an update command for each item in <paramref name="entities"/>, a single update command is created.</para>
/// </remarks>
public static int UpdateBatch<TEntity>( this Table<TEntity> table, IQueryable<TEntity> entities, Expression<Func<TEntity, TEntity>> evaluator ) where TEntity : class
{
DbCommand update = table.GetUpdateBatchCommand<TEntity>( entities, evaluator );
var parameters = from p in update.Parameters.Cast<DbParameter>()
select p.Value;
return table.Context.ExecuteCommand( update.CommandText, parameters.ToArray() );
}
/// <summary>
/// Immediately updates all entities in the collection with a single update command based on a <typeparamref name="TEntity"/> created from a Lambda expression.
/// </summary>
/// <typeparam name="TEntity">Represents the object type for rows contained in <paramref name="table"/>.</typeparam>
/// <param name="table">Represents a table for a particular type in the underlying database containing rows are to be updated.</param>
/// <param name="filter">Represents a filter of items to be updated in <paramref name="table"/>.</param>
/// <param name="evaluator">A Lambda expression returning a <typeparamref name="TEntity"/> that defines the update assignments to be performed on each item in <paramref name="entities"/>.</param>
/// <returns>The number of rows updated in the database.</returns>
/// <remarks>
/// <para>Similiar to stored procedures, and opposite from similiar InsertAllOnSubmit, rows provided in <paramref name="entities"/> will be updated immediately with no need to call <see cref="DataContext.SubmitChanges()"/>.</para>
/// <para>Additionally, to improve performance, instead of creating an update command for each item in <paramref name="entities"/>, a single update command is created.</para>
/// </remarks>
public static int UpdateBatch<TEntity>( this Table<TEntity> table, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TEntity>> evaluator ) where TEntity : class
{
return table.UpdateBatch( table.Where( filter ), evaluator );
}
/// <summary>
/// Returns the Transact SQL string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to perform the query's select statement.
/// </summary>
/// <param name="context">The DataContext to execute the batch select against.</param>
/// <param name="query">Represents the SELECT query to execute.</param>
/// <returns>Returns the Transact SQL string representation of the <see cref="DbCommand.CommandText"/> along with <see cref="DbCommand.Parameters"/> if present.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
public static string PreviewSQL( this DataContext context, IQueryable query )
{
var cmd = context.GetCommand( query );
return cmd.PreviewCommandText( true );
}
/// <summary>
/// Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to perform the query's select statement.
/// </summary>
/// <param name="context">The DataContext to execute the batch select against.</param>
/// <param name="query">Represents the SELECT query to execute.</param>
/// <returns>Returns a string representation of the <see cref="DbCommand.CommandText"/> along with <see cref="DbCommand.Parameters"/> if present.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
public static string PreviewCommandText( this DataContext context, IQueryable query )
{
var cmd = context.GetCommand( query );
return cmd.PreviewCommandText( false);
}
/// <summary>
/// Returns a string representation the LINQ <see cref="IProvider"/> command text and parameters used that would be issued to perform the query's select statement.
/// </summary>
/// <param name="context">The DataContext to execute the batch select against.</param>
/// <param name="query">Represents the SELECT query to execute.</param>
/// <returns>Returns a string representation of the <see cref="DbCommand.CommandText"/> along with <see cref="DbCommand.Parameters"/> if present.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
public static string TranslateToSqlCommand( this DataContext context, IQueryable query )
{
var cmd = context.GetCommand( query );
var output = new StringBuilder();
var statements = cmd.CommandText.Replace( "\r\n", "\r" ).Split( '\r' );
statements = statements.Take( 1 ).Select( s => "\"" + s + "\"" ).Concat(
statements.Skip( 1 ).Select( s => " \"" + s + "\"" ) ).ToArray();
output.AppendLine( "#region - SQL -\r\n" );
output.AppendLine( string.Format( "var sqlText = {0};", string.Join( " +\r\n", statements ) ) );
output.AppendLine( "#endregion\r\n" );
output.AppendLine( "using ( var connection = new SqlConnection( ... ) )" );
output.AppendLine( "{" );
output.AppendLine( "\tusing ( var command = new SqlCommand( sqlText, connection ) )" );
output.AppendLine( "\t{" );
if ( cmd.Parameters.Count > 0 )
{
foreach ( DbParameter p in cmd.Parameters )
{
var p2 = p as SqlParameter;
output.AppendLine( string.Format( "\t\tcommand.Parameters.Add( new SqlParameter( \"{0}\", {1} ) );", p.ParameterName, GetParameterTransactValue( p, p2, true ) ) );
}
output.AppendLine( "" );
output.AppendLine( "\t\t\tusing ( var reader = command.ExecuteReader() )" );
output.AppendLine( "\t\t\t{" );
output.AppendLine( "\t\t\t}" );
}
output.AppendLine( "\t}" );
output.AppendLine( "}" );
return output.ToString();
}
/// <summary>
/// Returns a string representation of the <see cref="DbCommand.CommandText"/> along with <see cref="DbCommand.Parameters"/> if present.
/// </summary>
/// <param name="cmd">The <see cref="DbCommand"/> to analyze.</param>
/// <param name="forTransactSQL">Whether or not the text should be formatted as 'logging' similiar to LINQ to SQL output, or in valid Transact SQL syntax ready for use with a 'query analyzer' type tool.</param>
/// <returns>Returns a string representation of the <see cref="DbCommand.CommandText"/> along with <see cref="DbCommand.Parameters"/> if present.</returns>
/// <remarks>This method is useful for debugging purposes or when used in other utilities such as LINQPad.</remarks>
private static string PreviewCommandText( this DbCommand cmd, bool forTransactSQL )
{
var output = new StringBuilder();
if ( !forTransactSQL ) output.AppendLine( cmd.CommandText );
foreach ( DbParameter parameter in cmd.Parameters )
{
int num = 0;
int num2 = 0;
PropertyInfo property = parameter.GetType().GetProperty( "Precision" );
if ( property != null )
{
num = (int)Convert.ChangeType( property.GetValue( parameter, null ), typeof( int ), CultureInfo.InvariantCulture );
}
PropertyInfo info2 = parameter.GetType().GetProperty( "Scale" );
if ( info2 != null )
{
num2 = (int)Convert.ChangeType( info2.GetValue( parameter, null ), typeof( int ), CultureInfo.InvariantCulture );
}
SqlParameter parameter2 = parameter as SqlParameter;
if ( forTransactSQL )
{
output.AppendFormat( "DECLARE {0} {1}{2}; SET {0} = {3}\r\n",
new object[] {
parameter.ParameterName,
( parameter2 == null ) ? parameter.DbType.ToString() : parameter2.SqlDbType.ToString(),
( parameter.Size > 0 ) ? "( " + parameter.Size.ToString( CultureInfo.CurrentCulture ) + " )" : "",
GetParameterTransactValue( parameter, parameter2 ) } );
}
else
{
output.AppendFormat( "-- {0}: {1} {2} (Size = {3}; Prec = {4}; Scale = {5}) [{6}]\r\n", new object[] { parameter.ParameterName, parameter.Direction, ( parameter2 == null ) ? parameter.DbType.ToString() : parameter2.SqlDbType.ToString(), parameter.Size.ToString( CultureInfo.CurrentCulture ), num, num2, ( parameter2 == null ) ? parameter.Value : parameter2.SqlValue } );
}
}
if ( forTransactSQL ) output.Append( "\r\n" + cmd.CommandText );
return output.ToString();
}
private static string GetParameterTransactValue( DbParameter parameter, SqlParameter parameter2, bool forSqlConversion = false )
{
if ( parameter2 == null ) return parameter.Value.ToString(); // Not going to deal with NON SQL parameters.
switch( parameter2.SqlDbType )
{
case SqlDbType.Char:
case SqlDbType.Date:
case SqlDbType.DateTime:
case SqlDbType.DateTime2:
case SqlDbType.NChar:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.SmallDateTime:
case SqlDbType.Text:
case SqlDbType.VarChar:
case SqlDbType.UniqueIdentifier:
return string.Format( "{0}{1}{0}", forSqlConversion ? "\"" : "'", parameter2.SqlValue );
default:
return parameter2.SqlValue.ToString();
}
}
private static DbCommand GetDeleteBatchCommand<TEntity>( this Table<TEntity> table, IQueryable<TEntity> entities ) where TEntity : class
{
var deleteCommand = table.Context.GetCommand( entities );
deleteCommand.CommandText = string.Format( "DELETE {0}\r\n", table.GetDbName() ) + GetBatchJoinQuery<TEntity>( table, entities );
return deleteCommand;
}
private static DbCommand GetUpdateBatchCommand<TEntity>( this Table<TEntity> table, IQueryable<TEntity> entities, Expression<Func<TEntity, TEntity>> evaluator ) where TEntity : class
{
var updateCommand = table.Context.GetCommand( entities );
var setSB = new StringBuilder();
int memberInitCount = 1;
// Process the MemberInitExpression (there should only be one in the evaluator Lambda) to convert the expression tree
// into a valid DbCommand. The Visit<> method will only process expressions of type MemberInitExpression and requires
// that a MemberInitExpression be returned - in our case we'll return the same one we are passed since we are building
// a DbCommand and not 'really using' the evaluator Lambda.
evaluator.Visit<MemberInitExpression>( delegate( MemberInitExpression expression )
{
if ( memberInitCount > 1 )
{
throw new NotImplementedException( "Currently only one MemberInitExpression is allowed for the evaluator parameter." );
}
memberInitCount++;
setSB.Append( GetDbSetStatement<TEntity>( expression, table, updateCommand ) );
return expression; // just return passed in expression to keep 'visitor' happy.
} );
// Complete the command text by concatenating bits together.
updateCommand.CommandText = string.Format( "UPDATE {0}\r\n{1}\r\n\r\n{2}",
table.GetDbName(), // Database table name
setSB.ToString(), // SET fld = {}, fld2 = {}, ...
GetBatchJoinQuery<TEntity>( table, entities ) ); // Subquery join created from entities command text
if ( updateCommand.CommandText.IndexOf( "[arg0]" ) >= 0 || updateCommand.CommandText.IndexOf( "NULL AS [EMPTY]" ) >= 0 )
{
// TODO (Chris): Probably a better way to determine this by using an visitor on the expression before the
// var selectExpression = Expression.Call... method call (search for that) and see which funcitons
// are being used and determine if supported by LINQ to SQL
throw new NotSupportedException( string.Format( "The evaluator Expression<Func<{0},{0}>> has processing that needs to be performed once the query is returned (i.e. string.Format()) and therefore can not be used during batch updating.", table.GetType() ) );
}
return updateCommand;
}
private static string GetDbSetStatement<TEntity>( MemberInitExpression memberInitExpression, Table<TEntity> table, DbCommand updateCommand ) where TEntity : class
{
var entityType = typeof( TEntity );
if ( memberInitExpression.Type != entityType )
{
throw new NotImplementedException( string.Format( "The MemberInitExpression is intializing a class of the incorrect type '{0}' and it should be '{1}'.", memberInitExpression.Type, entityType ) );
}
var setSB = new StringBuilder();
var tableName = table.GetDbName();
var metaTable = table.Context.Mapping.GetTable( entityType );
// Used to look up actual field names when MemberAssignment is a constant,
// need both the Name (matches the property name on LINQ object) and the
// MappedName (db field name).
var dbCols = from mdm in metaTable.RowType.DataMembers
select new { mdm.MappedName, mdm.Name };
// Walk all the expression bindings and generate SQL 'commands' from them. Each binding represents a property assignment
// on the TEntity object initializer Lambda expression.
foreach ( var binding in memberInitExpression.Bindings )
{
var assignment = binding as MemberAssignment;
if ( binding == null )
{
throw new NotImplementedException( "All bindings inside the MemberInitExpression are expected to be of type MemberAssignment." );
}
// TODO (Document): What is this doing? I know it's grabbing existing parameter to pass into Expression.Call() but explain 'why'
// I assume it has something to do with fact we can't just access the parameters of assignment.Expression?
// Also, any concerns of whether or not if there are two params of type entity type?
ParameterExpression entityParam = null;
assignment.Expression.Visit<ParameterExpression>( delegate( ParameterExpression p ) { if ( p.Type == entityType ) entityParam = p; return p; } );
// Get the real database field name. binding.Member.Name is the 'property' name of the LINQ object
// so I match that to the Name property of the table mapping DataMembers.
string name = binding.Member.Name;
var dbCol = ( from c in dbCols
where c.Name == name
select c ).FirstOrDefault();
if ( dbCol == null )
{
throw new ArgumentOutOfRangeException( name, string.Format( "The corresponding field on the {0} table could not be found.", tableName ) );
}
var mappedName = dbCol.MappedName.StartsWith( "[" ) ? dbCol.MappedName : string.Format( "[{0}]", dbCol.MappedName );
// If entityParam is NULL, then no references to other columns on the TEntity row and need to eval 'constant' value...
if ( entityParam == null )
{
// Compile and invoke the assignment expression to obtain the contant value to add as a parameter.
var constant = Expression.Lambda( assignment.Expression, null ).Compile().DynamicInvoke();
// use the MappedName from the table mapping DataMembers - that is field name in DB table.
if ( constant == null )
{
setSB.AppendFormat( "{0} = null, ", mappedName );
}
else
{
// Add new parameter with massaged name to avoid clashes.
setSB.AppendFormat( "{0} = @p{1}, ", mappedName, updateCommand.Parameters.Count );
updateCommand.Parameters.Add( new SqlParameter( string.Format( "@p{0}", updateCommand.Parameters.Count ), constant ) );
}
}
else
{
// TODO (Documentation): Explain what we are doing here again, I remember you telling me why we have to call but I can't remember now.
// Wny are we calling Expression.Call and what are we passing it? Below comments are just 'made up' and probably wrong.
// Create a MethodCallExpression which represents a 'simple' select of *only* the assignment part (right hand operator) of
// of the MemberInitExpression.MemberAssignment so that we can let the Linq Provider do all the 'sql syntax' generation for
// us.
//
// For Example: TEntity.Property1 = TEntity.Property1 + " Hello"
// This selectExpression will be only dealing with TEntity.Property1 + " Hello"
var selectExpression = Expression.Call(
typeof( Queryable ),
"Select",
new Type[] { entityType, assignment.Expression.Type },
// TODO (Documentation): How do we know there are only 'two' parameters? And what is Expression.Lambda
// doing? I assume it's returning a type of assignment.Expression.Type to match above?
Expression.Constant( table ),
Expression.Lambda( assignment.Expression, entityParam ) );
setSB.AppendFormat( "{0} = {1}, ",
mappedName,
GetDbSetAssignment( table, selectExpression, updateCommand, name ) );
}
}
var setStatements = setSB.ToString();
return "SET " + setStatements.Substring( 0, setStatements.Length - 2 ); // remove ', '
}
/// <summary>
/// Some LINQ Query syntax is invalid because SQL (or whomever the provider is) can not translate it to its native language.
/// DataContext.GetCommand() does not detect this, only IProvider.Execute or IProvider.Compile call the necessary code to
/// check this. This function invokes the IProvider.Compile to make sure the provider can translate the expression.
/// </summary>
/// <remarks>
/// An example of a LINQ query that previously 'worked' in the *Batch methods but needs to throw an exception is something
/// like the following:
///
/// var pay =
/// from h in HistoryData
/// where h.his.Groups.gName == "Ochsner" && h.hisType == "pay"
/// select h;
///
/// HistoryData.UpdateBatchPreview( pay, h => new HistoryData { hisIndex = ( int.Parse( h.hisIndex ) - 1 ).ToString() } ).Dump();
///
/// The int.Parse is not valid and needs to throw an exception like:
///
/// Could not translate expression '(Parse(p.hisIndex) - 1).ToString()' into SQL and could not treat it as a local expression.
///
/// Unfortunately, the IProvider.Compile is internal and I need to use Reflection to call it (ugh). I've several e-mails sent into
/// MS LINQ team members and am waiting for a response and will correct/improve code as soon as possible.
/// </remarks>
private static void ValidateExpression( ITable table, Expression expression )
{
// Simply compile the expression to see if it will work.
// Needed to change this to use expression tree. Original code (below) could fail with DataContextInterceptor.
var compile = Expression.Call(
Expression.Property( Expression.Constant( table.Context ), "Provider" ),
"Compile",
null,
Expression.Constant( expression ) );