-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathSourceInjectedQuery.cs
More file actions
931 lines (773 loc) · 32.6 KB
/
SourceInjectedQuery.cs
File metadata and controls
931 lines (773 loc) · 32.6 KB
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
using Shouldly;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using Xunit;
namespace AutoMapper.Extensions.ExpressionMapping.UnitTests.Impl
{
public class SourceInjectedQuery : AutoMapperSpecBase
{
readonly Source[] _source =
[
new Source {SrcValue = 5, InttoStringValue = 5},
new Source {SrcValue = 4, InttoStringValue = 4},
new Source {SrcValue = 7, InttoStringValue = 7}
];
public class Source
{
public int SrcValue { get; set; }
public string StringValue { get; set; }
public int InttoStringValue { get; set; }
public string[] Strings { get; set; }
}
public class Destination
{
public int DestValue { get; set; }
public string StringValue { get; set; }
public string InttoStringValue { get; set; }
public string[] Strings { get; set; }
}
protected override MapperConfiguration Configuration { get; } = ConfigurationHelper.GetMapperConfiguration(cfg =>
{
cfg.CreateMap<Destination, Source>()
.ForMember(s => s.SrcValue, opt => opt.MapFrom(d => d.DestValue))
.ReverseMap()
.ForMember(d => d.DestValue, opt => opt.MapFrom(s => s.SrcValue));
});
[Fact]
public void Shoud_support_const_result()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>()
.Where(s => s.DestValue > 6);
result.Count().ShouldBe(1);
result.Any(s => s.DestValue > 6).ShouldBeTrue();
}
[Fact]
public void Shoud_use_destination_elementType()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>();
result.ElementType.ShouldBe(typeof(Destination));
result = result.Where(s => s.DestValue > 3);
result.ElementType.ShouldBe(typeof(Destination));
}
[Fact]
public void Shoud_support_single_item_result()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>();
result.First(s => s.DestValue > 6).ShouldBeOfType<Destination>();
}
[Fact]
public void Shoud_support_IEnumerable_result()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>()
.Where(s => s.DestValue > 6);
List<Destination> list = [.. result];
}
[Fact]
public void Shoud_convert_source_item_to_destination()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>();
var destItem = result.First(s => s.DestValue == 7);
var sourceItem = _source.First(s => s.SrcValue == 7);
destItem.DestValue.ShouldBe(sourceItem.SrcValue);
}
[Fact]
public void Shoud_support_order_by_statement_result()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>()
.OrderByDescending(s => s.DestValue);
result.First().DestValue.ShouldBe(_source.Max(s => s.SrcValue));
}
[Fact]
public void Shoud_support_any_stupid_thing_you_can_throw_at_it()
{
var result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 7).Take(1)
.OrderByDescending(s => s.DestValue).Select(s => s.DestValue);
result.First().ShouldBe(_source.Max(s => s.SrcValue));
}
[Fact]
public void Shoud_support_string_return_type()
{
var result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 7).Take(1)
.OrderByDescending(s => s.DestValue).Select(s => s.StringValue);
result.First().ShouldBe(null);
}
[Fact]
public void Shoud_support_enumerable_return_type()
{
var result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 7).Take(1)
.OrderByDescending(s => s.DestValue).Select(s => s.Strings);
result.First().ShouldBe(null);
}
[Fact]
public void Shoud_support_enumerable_return_type_with_result()
{
var source = new[]
{
new Source {SrcValue = 5, Strings = ["lala5", "lili5"]},
new Source {SrcValue = 4, Strings = ["lala4", "lili4"]},
new Source {SrcValue = 7, Strings = ["lala7", "lili7"]}
};
var result = source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 5).Take(2)
.OrderByDescending(s => s.DestValue).Select(s => s.Strings);
var item = result.First();
item.Length.ShouldBe(2);
item.All(x => x.EndsWith("7")).ShouldBe(true);
}
[Fact]
public void Shoud_support_any_stupid_thing_you_can_throw_at_it_with_annonumus_types()
{
var result = _source.AsQueryable()
.UseAsDataSource(Mapper).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 7).Take(1)
.OrderByDescending(s => s.DestValue).Select(s => new { A = s.DestValue });
result.First().A.ShouldBe(_source.Max(s => s.SrcValue));
}
readonly User[] _source2 =
[
new User { UserId = 2, Account = new Account(){ Id = 4,Things = {new Thing(){Bar = "Bar"}, new Thing(){ Bar ="Bar 2"}}}},
new User { UserId = 1, Account = new Account(){ Id = 3,Things = {new Thing(){Bar = "Bar 3"}, new Thing(){ Bar ="Bar 4"}}}},
];
[Fact]
public void Map_select_method()
{
var mapper = SetupAutoMapper();
var result = _source2.AsQueryable()
.UseAsDataSource(mapper).For<UserModel>().OrderBy(s => s.Id).ThenBy(s => s.FullName).Select(s => (object)s.AccountModel.ThingModels.Select(b => b.BarModel));
(result.First() as IEnumerable<string>).Last().ShouldBe("Bar 4");
}
[Fact]
public void Map_orderBy_thenBy_expression()
{
var mapper = SetupAutoMapper();
var result = _source2.AsQueryable()
.UseAsDataSource(mapper).For<UserModel>().Select(s => (object)s.AccountModel.ThingModels);
(result.First() as IEnumerable<Thing>).Last().Bar.ShouldBe("Bar 2");
}
[Fact]
public void Shoud_convert_source_item_to_destination_toList()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>();
var destItem = result.ToList().First(s => s.DestValue == 7);
var sourceItem = _source.First(s => s.SrcValue == 7);
destItem.DestValue.ShouldBe(sourceItem.SrcValue);
}
[Fact]
public void Shoud_support_order_by_statement_result_toList()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>()
.OrderByDescending(s => s.DestValue);
result.ToList().First().DestValue.ShouldBe(_source.Max(s => s.SrcValue));
}
[Fact]
public void Shoud_support_any_stupid_thing_you_can_throw_at_it_toList()
{
var result = _source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 7).Take(1)
.OrderByDescending(s => s.DestValue).Select(s => s.DestValue);
var list = result.ToList();
list.First().ShouldBe(_source.Max(s => s.SrcValue));
}
[Fact]
public void Shoud_support_string_return_type_toList()
{
var result = _source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 7).Take(1)
.OrderByDescending(s => s.DestValue).Select(s => s.StringValue);
result.ToList().First().ShouldBe(null);
}
[Fact]
public void Shoud_support_enumerable_return_type_toList()
{
foreach (var src in _source)
{
src.Strings = null;
}
var result = _source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 7).Take(1)
.OrderByDescending(s => s.DestValue).Select(s => s.Strings);
var list = result.ToList();
list.First().ShouldBeNull(); // must be null as source values are null as well and Destination does not create empty array in constructor
}
[Fact]
public void Shoud_support_enumerable_return_type_with_result_toList()
{
var source = new[]
{
new Source {SrcValue = 5, Strings = ["lala5", "lili5"]},
new Source {SrcValue = 4, Strings = ["lala4", "lili4"]},
new Source {SrcValue = 7, Strings = ["lala7", "lili7"]}
};
var result = source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 5).Take(2)
.OrderByDescending(s => s.DestValue).Select(s => s.Strings);
var list = result.ToList();
list.Count.ShouldBe(2);
list[0].ShouldNotBeNull();
list[0].Length.ShouldBe(2);
list[0].All(x => x.EndsWith("7")).ShouldBe(true);
list[1].ShouldNotBeNull();
list[1].Length.ShouldBe(2);
list[1].All(x => x.EndsWith("5")).ShouldBe(true);
}
[Fact]
public void Shoud_support_any_stupid_thing_you_can_throw_at_it_with_annonumus_types_toList()
{
var result = _source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>()
.Where(s => 5.ToString() == "5" && s.DestValue.ToString() != "0")
.OrderBy(s => s.DestValue).SkipWhile(d => d.DestValue < 7).Take(1)
.OrderByDescending(s => s.DestValue).Select(s => new { A = s.DestValue });
result.ToList().First().A.ShouldBe(_source.Max(s => s.SrcValue));
}
[Fact]
public void Map_select_method_toList()
{
var mapper = SetupAutoMapper();
var result = _source2.AsQueryable()
.UseAsDataSource(mapper).For<UserModel>().OrderBy(s => s.Id).ThenBy(s => s.FullName).Select(s => (object)s.AccountModel.ThingModels.Select(b => b.BarModel));
(result.ToList().First() as IEnumerable<string>).Last().ShouldBe("Bar 4");
}
[Fact]
public void Map_orderBy_thenBy_expression_toList()
{
var mapper = SetupAutoMapper();
var result = _source2.AsQueryable()
.UseAsDataSource(mapper).For<UserModel>().Select(s => (object)s.AccountModel.ThingModels);
(result.ToList().First() as IEnumerable<Thing>).Last().Bar.ShouldBe("Bar 2");
}
[Fact]
public void CanMapCyclicObjectGraph()
{
// Arrange
var mapper = SetupAutoMapper();
var master = new Master()
{
Name = "Harry Marry",
Id = Guid.NewGuid(),
};
var detail = new Detail()
{
Id = Guid.NewGuid(),
Name = "Test Order",
Master = master,
};
master.Details.Add(detail);
// Act
var dto = mapper.Map<DetailCyclicDto>(detail);
// Assert
SourceInjectedQuery.AssertValidDtoGraph(detail, master, dto);
}
[Fact]
public void CanMapCaclicExpressionGraph()
{
// Arrange
var mapper = SetupAutoMapper();
var master = new Master()
{
Name = "Harry Marry",
Id = Guid.NewGuid(),
};
var detail = new Detail()
{
Id = Guid.NewGuid(),
Name = "Test Order",
Master = master,
};
master.Details.Add(detail);
var detailQuery = new List<Detail> { detail }.AsQueryable();
// Act
var detailDtoQuery = detailQuery.UseAsDataSource(mapper)
.For<DetailCyclicDto>();
// Assert
var dto = detailDtoQuery.Single();
SourceInjectedQuery.AssertValidDtoGraph(detail, master, dto);
}
[Fact]
public void CanMapCaclicExpressionGraph_WithPropertyFilter()
{
// Arrange
var mapper = SetupAutoMapper();
var master = new Master()
{
Name = "Harry Marry",
Id = Guid.NewGuid(),
};
var detail = new Detail()
{
Id = Guid.NewGuid(),
Name = "Test Order",
Master = master,
};
master.Details.Add(detail);
var detailQuery = new List<Detail> { detail }.AsQueryable();
// Act
var detailDtoQuery = detailQuery.UseAsDataSource(mapper)
.For<DetailCyclicDto>()
.Where(d => d.Name.EndsWith("rder"));
// Assert
var dto = detailDtoQuery.Single();
SourceInjectedQuery.AssertValidDtoGraph(detail, master, dto);
}
[Fact]
public void CanMapCaclicExpressionGraph_WithPropertyPathEqualityFilter_Single()
{
// Arrange
var mapper = SetupAutoMapper();
var master = new Master()
{
Name = "Harry Marry",
Id = Guid.NewGuid(),
};
var detail = new Detail()
{
Id = Guid.NewGuid(),
Name = "Test Order",
Master = master,
};
master.Details.Add(detail);
var detailQuery = new List<Detail> { detail }.AsQueryable();
// Act
var detailDtoQuery = detailQuery.UseAsDataSource(mapper)
.For<DetailCyclicDto>()
.Where(d => d.Master.Name == "Harry Marry");
// Assert
var dto = detailDtoQuery.Single();
SourceInjectedQuery.AssertValidDtoGraph(detail, master, dto);
}
[Fact]
[Description("Fix for issue #882")]
public void Should_support_propertypath_expressons_with_equally_named_properties()
{
// Arrange
var mapper = SetupAutoMapper();
var master = new Master { Id = Guid.NewGuid(), Name = "Harry Marry" };
var detail = new Detail { Id = Guid.NewGuid(), Master = master, Name = "Some detail" };
master.Details.Add(detail);
var source = new List<Detail> { detail };
// Act
var detailDtoQuery = source.AsQueryable().UseAsDataSource(mapper)
.For<DetailDto>()
.Where(d => d.Master.Name == "Harry Marry");
// Assert
detailDtoQuery.ToList().Count.ShouldBe(1);
}
private static void AssertValidDtoGraph(Detail detail, Master master, DetailCyclicDto dto)
{
dto.ShouldNotBeNull();
detail.Id.ShouldBe(dto.Id);
detail.Master.ShouldNotBeNull();
master.Details.ShouldNotBeEmpty();
detail.Master.Id.ShouldBe(master.Id);
dto.Master.Details.Single().Id.ShouldBe(dto.Id, "Dto was not added to inner collection");
//dto.GetHashCode().ShouldBe(dto.Master.Details.Single().GetHashCode()); // "Underlying provider always creates two distinct instances"
}
[Fact]
public void SupportsParmeterization()
{
// Arrange
int value = 0;
Expression<Func<SourceWithParams, int>> sourceMember = src => value + 5;
var config = ConfigurationHelper.GetMapperConfiguration(cfg => cfg.CreateMap<SourceWithParams, DestWithParams>()
.ForMember(dest => dest.Value, opt => opt.MapFrom(sourceMember)));
var mapper = new Mapper(config);
var source = new[]
{
new SourceWithParams()
}.AsQueryable();
// Act
var result = source.UseAsDataSource(mapper).For<DestWithParams>(new Dictionary<string, object> { { "value", 10 } }).ToArray();
// Assert
result.ShouldNotBeNull();
result.ShouldNotBeEmpty();
result.Single().Value.ShouldBe(15);
}
[Fact]
public void SupportsParmeterization_DoesNotCacheParameter()
{
// Arrange
int value = 0;
Expression<Func<SourceWithParams, int>> sourceMember = src => value + 5;
var config = ConfigurationHelper.GetMapperConfiguration(cfg => cfg.CreateMap<SourceWithParams, DestWithParams>()
.ForMember(dest => dest.Value, opt => opt.MapFrom(sourceMember)));
var mapper = new Mapper(config);
var source = new[]
{
new SourceWithParams()
}.AsQueryable();
// Act
var result1 = source.UseAsDataSource(mapper).For<DestWithParams>(new Dictionary<string, object> { { "value", 10 } }).ToArray();
var result = source.UseAsDataSource(mapper).For<DestWithParams>(new Dictionary<string, object> { { "value", 15 } }).ToArray();
// Assert
result1.ShouldNotBeNull();
result.ShouldNotBeNull();
result.ShouldNotBeEmpty();
result.Single().Value.ShouldBe(20);
}
[Fact]
public void SupportsParameterizationInQuery()
{
// Arrange
var sources = new List<ResourceWithPermissions>()
{
new() {
Title = "Resource 01",
Permissions =
[
new() {PermissionName = "Edit", UserId = 22},
new() {PermissionName = "Read", UserId = 4}
]
},
new() {
Title = "Resource 02",
Permissions =
[
new Permission {PermissionName = "Edit", UserId = 4}
]
},
new() {
Title = "Resource 03",
Permissions = []
}
};
// note:
// we need to create the mapping and the query in two distinct scopes (therefore action and func)
// so that we can declare a parameter (userId) that is independent of mapping and query definition.
// that way, in the query, we have a parameter which needs to be replaced.
// (in SourceInjectedQueryProvider.ConvertDestinationExpressionToSourceExpression)
var config = ConfigurationHelper.GetMapperConfiguration(cfg =>
{
// parameter defined in mapping part
long userId = default;
cfg.CreateMap<ResourceWithPermissions, ResourceDto>()
.ForMember(t => t.HasEditPermission,
o => o.MapFrom(s => s.Permissions.Any(p => p.PermissionName == "Edit" && p.UserId == userId)));
cfg.CreateMap<ResourceDto, ResourceWithPermissions>()
.ForMember(t => t.Permissions, o => o.Ignore());
});
var mapper = new Mapper(config);
var factoryFunc = new Func<IList<ResourceWithPermissions>, IQueryable<ResourceWithPermissions>>((list) =>
{
// same parameter defined in query part
long userId = default;
return list.AsQueryable().Where(r => r.Permissions.Any(p => p.UserId == userId));
});
var query = factoryFunc(sources)
.UseAsDataSource(mapper)
.For<ResourceDto>(new {userId = 4});
// Act
var results = query.ToList();
// Assert
results.ShouldNotBeNull();
results.ShouldNotBeEmpty();
results.Count.ShouldBe(2);
results[0].HasEditPermission.ShouldBeFalse();
results[1].HasEditPermission.ShouldBeTrue();
}
[Fact]
public void Shoud_convert_type_changes()
{
IQueryable<Destination> result = _source.AsQueryable()
.UseAsDataSource(Configuration).For<Destination>();
var destItem = result.First(s => s.InttoStringValue == "7");
var sourceItem = _source.First(s => s.InttoStringValue == 7);
destItem.DestValue.ShouldBe(sourceItem.SrcValue);
}
//[Fact(Skip="Conventions not available like this.")]
//public void Shoud_work_with_conventions()
//{
// //var mapper = ConfigurationHelper.GetMapperConfiguration(cfg => cfg.AddConditionalObjectMapper()
// // .Where((s, d) => s.Name == d.Name + "Model" || s.Name + "Model" == d.Name)).CreateMapper();
// //IQueryable<Destination> result = _source.AsQueryable()
// // .UseAsDataSource(Mapper).For<Destination>()
// // .Where(s => s.DestValue > 6);
// //result.Count().ShouldBe(1);
// //result.Any(s => s.DestValue > 6).ShouldBeTrue();
//}
[Fact]
public void Should_dispose_enumerator_when_arbitrary_projection_is_enumerated()
{
// Arrange
var mapper = SetupAutoMapper();
var source = new NotSingleQueryingEnumerable<Detail>();
// Act
_ = source.AsQueryable()
.UseAsDataSource(mapper).For<DetailDto>()
.Select(m => m.Name)
.ToList();
// Assert
NotRelationalDataReader.Instance.ShouldBeNull();
}
private static IMapper SetupAutoMapper()
{
var config = ConfigurationHelper.GetMapperConfiguration(cfg =>
{
cfg.CreateMap<User, UserModel>()
.ForMember(d => d.Id, opt => opt.MapFrom(s => s.UserId))
.ForMember(d => d.FullName, opt => opt.MapFrom(s => s.Name))
.ForMember(d => d.LoggedOn, opt => opt.MapFrom(s => s.IsLoggedOn ? "Y" : "N"))
.ForMember(d => d.IsOverEighty, opt => opt.MapFrom(s => s.Age > 80))
.ForMember(d => d.AccountName, opt => opt.MapFrom(s => s.Account == null ? string.Empty : string.Concat(s.Account.FirstName, " ", s.Account.LastName)))
.ForMember(d => d.AgeInYears, opt => opt.MapFrom(s => s.Age))
.ForMember(d => d.IsActive, opt => opt.MapFrom(s => s.Active))
.ForMember(d => d.AccountModel, opt => opt.MapFrom(s => s.Account));
cfg.CreateMap<UserModel, User>()
.ForMember(d => d.UserId, opt => opt.MapFrom(s => s.Id))
.ForMember(d => d.Name, opt => opt.MapFrom(s => s.FullName))
.ForMember(d => d.IsLoggedOn, opt => opt.MapFrom(s => s.LoggedOn.Equals("Y", StringComparison.CurrentCultureIgnoreCase)))
.ForMember(d => d.Age, opt => opt.MapFrom(s => s.AgeInYears))
.ForMember(d => d.Active, opt => opt.MapFrom(s => s.IsActive))
.ForMember(d => d.Account, opt => opt.MapFrom(s => s.AccountModel));
cfg.CreateMap<Account, AccountModel>()
.ForMember(d => d.Bal, opt => opt.MapFrom(s => s.Balance))
.ForMember(d => d.DateCreated, opt => opt.MapFrom(s => s.CreateDate))
.ForMember(d => d.ComboName, opt => opt.MapFrom(s => string.Concat(s.FirstName, " ", s.LastName)))
.ForMember(d => d.ThingModels, opt => opt.MapFrom(s => s.Things));
cfg.CreateMap<AccountModel, Account>()
.ForMember(d => d.Balance, opt => opt.MapFrom(s => s.Bal))
.ForMember(d => d.Things, opt => opt.MapFrom(s => s.ThingModels));
cfg.CreateMap<Thing, ThingModel>()
.ForMember(d => d.FooModel, opt => opt.MapFrom(s => s.Foo))
.ForMember(d => d.BarModel, opt => opt.MapFrom(s => s.Bar));
cfg.CreateMap<ThingModel, Thing>()
.ForMember(d => d.Foo, opt => opt.MapFrom(s => s.FooModel))
.ForMember(d => d.Bar, opt => opt.MapFrom(s => s.BarModel));
cfg.CreateMap<Master, MasterDto>().ReverseMap();
cfg.CreateMap<Detail, DetailDto>().ReverseMap();
// dtos with cyclic references that would cause a stackoverflow exception upon projection mapping
cfg.CreateMap<Master, MasterCyclicDto>().PreserveReferences();
cfg.CreateMap<MasterCyclicDto, Master>().PreserveReferences();
cfg.CreateMap<Detail, DetailCyclicDto>().PreserveReferences();
cfg.CreateMap<DetailCyclicDto, Detail>().PreserveReferences();
});
return config.CreateMapper();
}
}
public class Account
{
public Account()
{
Things = [];
}
public int Id { get; set; }
public double Balance { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime CreateDate { get; set; }
public ICollection<Thing> Things { get; set; }
}
public class AccountModel
{
public AccountModel()
{
ThingModels = [];
}
public int Id { get; set; }
public double Bal { get; set; }
public string ComboName { get; set; }
public DateTime DateCreated { get; set; }
public ICollection<ThingModel> ThingModels { get; set; }
}
public class Thing
{
public int Foo { get; set; }
public string Bar { get; set; }
}
public class ThingModel
{
public int FooModel { get; set; }
public string BarModel { get; set; }
}
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public bool IsLoggedOn { get; set; }
public int Age { get; set; }
public bool Active { get; set; }
public Account Account { get; set; }
}
public class UserModel
{
public int Id { get; set; }
public string FullName { get; set; }
public string AccountName { get; set; }
public bool IsOverEighty { get; set; }
public string LoggedOn { get; set; }
public int AgeInYears { get; set; }
public bool IsActive { get; set; }
public AccountModel AccountModel { get; set; }
}
public class Master
{
public Master()
{
Details = [];
}
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Detail> Details { get; set; }
}
public class Detail
{
public Guid Id { get; set; }
public string Name { get; set; }
public Master Master { get; set; }
}
public class MasterDto
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class DetailDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public MasterDto Master { get; set; }
}
public class MasterCyclicDto
{
public MasterCyclicDto()
{
Details = [];
}
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<DetailCyclicDto> Details { get; set; }
}
public class DetailCyclicDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public MasterCyclicDto Master { get; set; }
}
public class SourceWithParams
{
}
public class DestWithParams
{
public int Value { get; set; }
}
public class ResourceWithPermissions
{
public string Title { get; set; }
public ICollection<Permission> Permissions { get; set; }
}
public class Permission
{
public Permission()
{
}
public Permission(string permissionName, long userId)
{
PermissionName = permissionName;
UserId = userId;
}
public long UserId { get; set; }
public string PermissionName { get; set; }
}
public class ResourceDto
{
public string Title { get; set; }
public bool HasEditPermission { get; set; }
}
public class NotRelationalDataReader : IDisposable
{
public static NotRelationalDataReader Instance { get; set; }
public NotRelationalDataReader()
{
Instance = this;
}
public void Dispose()
{
Instance = null;
GC.SuppressFinalize(this);
}
}
/// <remarks>
/// Based on <see href="https://github.com/dotnet/efcore/blob/08e5ebd/src/EFCore.Relational/Query/Internal/SingleQueryingEnumerable.cs">Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable<T></see>
/// for <see cref="Enumerator.MoveNext"/> and <see cref="Enumerator.Dispose"/>.
/// </remarks>
public class NotSingleQueryingEnumerable<T> : IQueryable<T>, IQueryProvider
{
public Type ElementType => throw new NotImplementedException();
public Expression Expression => Expression.Constant(this);
public IQueryProvider Provider => this;
public IQueryable CreateQuery(Expression expression)
{
return this;
}
public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
{
throw new NotImplementedException();
}
public object Execute(Expression expression)
{
throw new NotImplementedException();
}
public TResult Execute<TResult>(Expression expression)
{
throw new NotImplementedException();
}
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator();
}
private sealed class Enumerator : IEnumerator<T>
{
private NotRelationalDataReader _dataReader;
public T Current => throw new NotImplementedException();
object IEnumerator.Current => throw new NotImplementedException();
public void Dispose()
{
_dataReader?.Dispose();
_dataReader = null;
}
public bool MoveNext()
{
_dataReader ??= new NotRelationalDataReader();
return false;
}
public void Reset()
{
throw new NotImplementedException();
}
}
}
}