-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
SqlServerEndToEndTest.cs
2273 lines (1870 loc) · 68.7 KB
/
SqlServerEndToEndTest.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.CompilerServices;
// ReSharper disable StringStartsWithIsCultureSpecific
// ReSharper disable VirtualMemberCallInConstructor
// ReSharper disable ClassNeverInstantiated.Local
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore;
public class SqlServerEndToEndTest : IClassFixture<SqlServerFixture>
{
private const string DatabaseName = "SqlServerEndToEndTest";
protected SqlServerFixture Fixture { get; }
public SqlServerEndToEndTest(SqlServerFixture fixture)
{
Fixture = fixture;
Fixture.TestSqlLoggerFactory.Clear();
}
[ConditionalFact]
public void Can_use_decimal_and_byte_as_identity_columns()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var nownNum1 = new NownNum { Id = 77.0m, TheWalrus = "Crying" };
var nownNum2 = new NownNum { Id = 78.0m, TheWalrus = "Walrus" };
var numNum1 = new NumNum { TheWalrus = "I" };
var numNum2 = new NumNum { TheWalrus = "Am" };
var anNum1 = new AnNum { TheWalrus = "Goo goo" };
var anNum2 = new AnNum { TheWalrus = "g'joob" };
var adNum1 = new AdNum { TheWalrus = "Eggman" };
var adNum2 = new AdNum { TheWalrus = "Eggmen" };
var byteNownNum1 = new ByteNownNum { Id = 77, Lucy = "Tangerine" };
var byteNownNum2 = new ByteNownNum { Id = 78, Lucy = "Trees" };
var byteNum1 = new ByteNum { Lucy = "Marmalade" };
var byteNum2 = new ByteNum { Lucy = "Skies" };
var byteAnNum1 = new ByteAnNum { Lucy = "Cellophane" };
var byteAnNum2 = new ByteAnNum { Lucy = "Flowers" };
var byteAdNum1 = new ByteAdNum { Lucy = "Kaleidoscope" };
var byteAdNum2 = new ByteAdNum { Lucy = "Eyes" };
decimal[] preSaveValues;
byte[] preSaveByteValues;
var options = Fixture.CreateOptions(testDatabase);
using (var context = new NumNumContext(options))
{
context.Database.EnsureCreatedResiliently();
context.AddRange(
nownNum1, nownNum2, numNum1, numNum2, adNum1, adNum2, anNum1, anNum2,
byteNownNum1, byteNownNum2, byteNum1, byteNum2, byteAdNum1, byteAdNum2, byteAnNum1, byteAnNum2);
preSaveValues = [numNum1.Id, numNum2.Id, adNum1.Id, adNum2.Id, anNum1.Id, anNum2.Id];
preSaveByteValues = [byteNum1.Id, byteNum2.Id, byteAdNum1.Id, byteAdNum2.Id, byteAnNum1.Id, byteAnNum2.Id];
context.SaveChanges();
}
using (var context = new NumNumContext(options))
{
Assert.Equal(nownNum1.Id, context.NownNums.Single(e => e.TheWalrus == "Crying").Id);
Assert.Equal(nownNum2.Id, context.NownNums.Single(e => e.TheWalrus == "Walrus").Id);
Assert.Equal(77.0m, nownNum1.Id);
Assert.Equal(78.0m, nownNum2.Id);
Assert.Equal(numNum1.Id, context.NumNums.Single(e => e.TheWalrus == "I").Id);
Assert.Equal(numNum2.Id, context.NumNums.Single(e => e.TheWalrus == "Am").Id);
Assert.NotEqual(numNum1.Id, preSaveValues[0]);
Assert.NotEqual(numNum2.Id, preSaveValues[1]);
Assert.Equal(anNum1.Id, context.AnNums.Single(e => e.TheWalrus == "Goo goo").Id);
Assert.Equal(anNum2.Id, context.AnNums.Single(e => e.TheWalrus == "g'joob").Id);
Assert.NotEqual(adNum1.Id, preSaveValues[2]);
Assert.NotEqual(adNum2.Id, preSaveValues[3]);
Assert.Equal(adNum1.Id, context.AdNums.Single(e => e.TheWalrus == "Eggman").Id);
Assert.Equal(adNum2.Id, context.AdNums.Single(e => e.TheWalrus == "Eggmen").Id);
Assert.NotEqual(anNum1.Id, preSaveValues[4]);
Assert.NotEqual(anNum2.Id, preSaveValues[5]);
Assert.Equal(byteNownNum1.Id, context.ByteNownNums.Single(e => e.Lucy == "Tangerine").Id);
Assert.Equal(byteNownNum2.Id, context.ByteNownNums.Single(e => e.Lucy == "Trees").Id);
Assert.Equal(77, byteNownNum1.Id);
Assert.Equal(78, byteNownNum2.Id);
Assert.Equal(byteNum1.Id, context.ByteNums.Single(e => e.Lucy == "Marmalade").Id);
Assert.Equal(byteNum2.Id, context.ByteNums.Single(e => e.Lucy == "Skies").Id);
Assert.NotEqual(byteNum1.Id, preSaveByteValues[0]);
Assert.NotEqual(byteNum2.Id, preSaveByteValues[1]);
Assert.Equal(byteAnNum1.Id, context.ByteAnNums.Single(e => e.Lucy == "Cellophane").Id);
Assert.Equal(byteAnNum2.Id, context.ByteAnNums.Single(e => e.Lucy == "Flowers").Id);
Assert.NotEqual(byteAdNum1.Id, preSaveByteValues[2]);
Assert.NotEqual(byteAdNum2.Id, preSaveByteValues[3]);
Assert.Equal(byteAdNum1.Id, context.ByteAdNums.Single(e => e.Lucy == "Kaleidoscope").Id);
Assert.Equal(byteAdNum2.Id, context.ByteAdNums.Single(e => e.Lucy == "Eyes").Id);
Assert.NotEqual(byteAnNum1.Id, preSaveByteValues[4]);
Assert.NotEqual(byteAnNum2.Id, preSaveByteValues[5]);
}
}
private class NumNumContext(DbContextOptions options) : DbContext(options)
{
public DbSet<NownNum> NownNums { get; set; }
public DbSet<NumNum> NumNums { get; set; }
public DbSet<AnNum> AnNums { get; set; }
public DbSet<AdNum> AdNums { get; set; }
public DbSet<ByteNownNum> ByteNownNums { get; set; }
public DbSet<ByteNum> ByteNums { get; set; }
public DbSet<ByteAnNum> ByteAnNums { get; set; }
public DbSet<ByteAdNum> ByteAdNums { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<NumNum>()
.Property(e => e.Id)
.HasColumnType("numeric(18, 0)")
.UseIdentityColumn();
modelBuilder
.Entity<AdNum>()
.Property(e => e.Id)
.HasColumnType("decimal(10, 0)")
.ValueGeneratedOnAdd();
modelBuilder
.Entity<ByteNum>()
.Property(e => e.Id)
.UseIdentityColumn();
modelBuilder
.Entity<ByteAdNum>()
.Property(e => e.Id)
.ValueGeneratedOnAdd();
modelBuilder
.Entity<NownNum>()
.Property(e => e.Id)
.HasColumnType("numeric(18, 0)");
}
}
private class NownNum
{
public decimal Id { get; set; }
public string TheWalrus { get; set; }
}
private class NumNum
{
public decimal Id { get; set; }
public string TheWalrus { get; set; }
}
private class AnNum
{
[Column(TypeName = "decimal(18, 0)")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public decimal Id { get; set; }
public string TheWalrus { get; set; }
}
private class AdNum
{
public decimal Id { get; set; }
public string TheWalrus { get; set; }
}
private class ByteNownNum
{
public byte Id { get; set; }
public string Lucy { get; set; }
}
private class ByteNum
{
public byte Id { get; set; }
public string Lucy { get; set; }
}
private class ByteAnNum
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public byte Id { get; set; }
public string Lucy { get; set; }
}
private class ByteAdNum
{
public byte Id { get; set; }
public string Lucy { get; set; }
}
[ConditionalFact] // Issue #29931
public void Can_use_SqlQuery_when_context_has_DbFunction()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
using (var context = new DbFunctionContext(options))
{
var result = context.Database
.SqlQueryRaw<RawResult>("SELECT Name from sys.databases")
.OrderBy(d => d.Name)
.ToList();
}
}
private class DbFunctionContext(DbContextOptions options) : DbContext(options)
{
[DbFunction("tvp", "dbo")]
public IQueryable<TvpResult> Tvp(int? storeid)
=> FromExpression(() => Tvp(storeid));
protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<TvpResult>().HasNoKey();
}
private class TvpResult
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal Total { get; set; }
}
private class RawResult
{
public string Name { get; set; }
}
[ConditionalFact]
public void Can_use_string_enum_or_byte_array_as_key()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var sNum1 = new SNum { TheWalrus = "I" };
var sNum2 = new SNum { TheWalrus = "Am" };
var enNum1 = new EnNum { TheWalrus = "Goo goo", Id = ENum.BNum };
var enNum2 = new EnNum { TheWalrus = "g'joob", Id = ENum.CNum };
var bNum1 = new BNum { TheWalrus = "Eggman" };
var bNum2 = new BNum { TheWalrus = "Eggmen" };
var options = Fixture.CreateOptions(testDatabase);
using (var context = new ENumContext(options))
{
context.Database.EnsureCreatedResiliently();
context.AddRange(sNum1, sNum2, enNum1, enNum2, bNum1, bNum2);
context.SaveChanges();
}
using (var context = new ENumContext(options))
{
Assert.Equal(sNum1.Id, context.SNums.Single(e => e.TheWalrus == "I").Id);
Assert.Equal(sNum2.Id, context.SNums.Single(e => e.TheWalrus == "Am").Id);
Assert.Equal(enNum1.Id, context.EnNums.Single(e => e.TheWalrus == "Goo goo").Id);
Assert.Equal(enNum2.Id, context.EnNums.Single(e => e.TheWalrus == "g'joob").Id);
Assert.Equal(bNum1.Id, context.BNums.Single(e => e.TheWalrus == "Eggman").Id);
Assert.Equal(bNum2.Id, context.BNums.Single(e => e.TheWalrus == "Eggmen").Id);
}
}
[ConditionalFact]
public void Can_remove_multiple_byte_array_as_key()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var bNum1 = new BNum { TheWalrus = "Eggman" };
var bNum2 = new BNum { TheWalrus = "Eggmen" };
var options = Fixture.CreateOptions(testDatabase);
using (var context = new ENumContext(options))
{
context.Database.EnsureCreatedResiliently();
context.AddRange(bNum1, bNum2);
context.SaveChanges();
}
using (var context = new ENumContext(options))
{
Assert.Equal(bNum1.Id, context.BNums.Single(e => e.TheWalrus == "Eggman").Id);
Assert.Equal(bNum2.Id, context.BNums.Single(e => e.TheWalrus == "Eggmen").Id);
context.RemoveRange(context.BNums);
context.SaveChanges();
}
}
private class ENumContext(DbContextOptions options) : DbContext(options)
{
public DbSet<SNum> SNums { get; set; }
public DbSet<EnNum> EnNums { get; set; }
public DbSet<BNum> BNums { get; set; }
}
[ConditionalFact]
public void Can_add_table_splitting_dependent_after_principal()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
EvaluationAction evaluationAction = null;
using (var context = new ProjectContext(options))
{
context.Database.EnsureCreatedResiliently();
evaluationAction = new EvaluationAction
{
Id = Guid.NewGuid().ToString(),
CreateId = "1",
UpdateId = "1"
};
context.EvaluationActions.Add(evaluationAction);
context.SaveChanges();
}
using (var context = new ProjectContext(options))
{
context.Database.EnsureCreatedResiliently();
var projectAction = new ProjectAction
{
Id = evaluationAction.Id,
CreateId = "1",
UpdateId = "1",
Name = "123123123123"
};
context.ProjectActions.Add(projectAction);
context.SaveChanges();
}
using (var context = new ProjectContext(options))
{
Assert.NotNull(context.ProjectActions.Single());
Assert.NotNull(context.EvaluationActions.Single());
}
}
[ConditionalFact]
public void Throws_when_adding_table_splitting_dependent_without_principal()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
using (var context = new ProjectContext(options))
{
context.Database.EnsureCreatedResiliently();
var projectAction = new ProjectAction
{
Id = Guid.NewGuid().ToString(),
CreateId = "1",
UpdateId = "1",
Name = "123123123123"
};
context.ProjectActions.Add(projectAction);
Assert.Throws<DbUpdateConcurrencyException>(() => context.SaveChanges());
}
}
private class ProjectContext(DbContextOptions options) : DbContext(options)
{
public DbSet<EvaluationAction> EvaluationActions { get; set; }
public DbSet<ProjectAction> ProjectActions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProjectAction>()
.ToTable("projectaction")
.HasOne(o => o.EvaluationAction).WithOne(o => o.ProjectAction)
.HasForeignKey<ProjectAction>(o => o.Id);
modelBuilder.Entity<ProjectAction>().Property(p => p.Name).IsRequired();
modelBuilder.Entity<EvaluationAction>()
.ToTable("projectaction");
}
}
private class ProjectAction
{
public string Id { get; set; }
public string CreateId { get; set; }
public string UpdateId { get; set; }
public string Name { get; set; }
public EvaluationAction EvaluationAction { get; set; }
}
private class EvaluationAction
{
public string Id { get; set; }
public string CreateId { get; set; }
public string UpdateId { get; set; }
public ProjectAction ProjectAction { get; set; }
}
private class SNum
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
public string TheWalrus { get; set; }
}
private class EnNum
{
public ENum Id { get; set; }
public string TheWalrus { get; set; }
}
private enum ENum
{
// ReSharper disable once UnusedMember.Local
ANum,
BNum,
CNum
}
private class BNum
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public byte[] Id { get; set; }
public string TheWalrus { get; set; }
}
[ConditionalFact]
public async Task Can_add_and_remove_entities_with_keys_of_different_type()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
using (var context = new CompositeKeysDbContext(options))
{
context.Database.EnsureCreatedResiliently();
var first = new Int32CompositeKeys { Id1 = 1, Id2 = 2 };
await context.AddAsync(first);
var second = new Int64CompositeKeys { Id1 = 1, Id2 = 2 };
await context.AddAsync(second);
await context.SaveChangesAsync();
}
using (var context = new CompositeKeysDbContext(options))
{
var first = context.Set<Int32CompositeKeys>().Single();
context.Remove(first);
var second = context.Set<Int64CompositeKeys>().Single();
context.Remove(second);
await context.SaveChangesAsync();
}
}
private class CompositeKeysDbContext(DbContextOptions options) : DbContext(options)
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Int32CompositeKeys>().HasKey(i => new { i.Id1, i.Id2 });
modelBuilder.Entity<Int64CompositeKeys>().HasKey(l => new { l.Id1, l.Id2 });
}
}
private class Int32CompositeKeys
{
public int Id1 { get; set; }
public int Id2 { get; set; }
}
private class Int64CompositeKeys
{
public long Id1 { get; set; }
public long Id2 { get; set; }
}
[ConditionalFact]
public void Can_insert_non_owner_principal_for_owned()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
using (var context = new FileContext(options))
{
context.Database.EnsureCreatedResiliently();
var category = new Category();
context.Categories.Add(category);
context.SaveChanges();
var fileMetadata = new FileMetadata();
context.FileMetadata.Add(fileMetadata);
category.Picture = new FileSource { FileId = fileMetadata.Id };
context.SaveChanges();
}
}
private class FileContext(DbContextOptions options) : DbContext(options)
{
public DbSet<FileMetadata> FileMetadata { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Category>(
builder =>
{
builder.OwnsOne(
x => x.Picture, fileSource =>
{
fileSource.HasOne<FileMetadata>().WithOne().HasForeignKey<FileSource>(x => x.FileId);
});
});
}
}
private sealed class FileMetadata
{
public Guid Id { get; set; }
}
private sealed class Category
{
public Guid Id { get; set; }
public FileSource Picture { get; set; }
}
private sealed class FileSource
{
public Guid? FileId { get; set; }
public bool Deleted { get; set; }
}
[ConditionalFact]
public async Task Can_insert_TPT_dependents_with_identity()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
using (var context = new CarContext(options))
{
context.Database.EnsureCreatedResiliently();
var ferrari = new Ferrari { Special = new Car() };
await context.AddAsync(ferrari);
await context.SaveChangesAsync();
Assert.NotNull(ferrari.Special);
}
}
private class CarContext(DbContextOptions options) : DbContext(options)
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>().ToTable("Car");
modelBuilder.Entity<Ferrari>().ToTable("Ferrari");
}
}
private class Car
{
public int Id { get; set; }
}
private class Ferrari : Car
{
public Car Special { get; set; }
}
[ConditionalFact]
public void Can_run_linq_query_on_entity_set()
{
using var testStore = SqlServerTestStore.GetNorthwindStore();
using var db = new NorthwindContext(Fixture.CreateOptions(testStore));
var results = db.Customers
.Where(c => c.CompanyName.StartsWith("A"))
.OrderByDescending(c => c.CustomerID)
.ToList();
Assert.Equal(4, results.Count);
Assert.Equal("AROUT", results[0].CustomerID);
Assert.Equal("ANTON", results[1].CustomerID);
Assert.Equal("ANATR", results[2].CustomerID);
Assert.Equal("ALFKI", results[3].CustomerID);
Assert.Equal("(171) 555-6750", results[0].Fax);
Assert.Null(results[1].Fax);
Assert.Equal("(5) 555-3745", results[2].Fax);
Assert.Equal("030-0076545", results[3].Fax);
}
[ConditionalFact]
public void Can_run_linq_query_on_entity_set_with_value_buffer_reader()
{
using var testStore = SqlServerTestStore.GetNorthwindStore();
using var db = new NorthwindContext(Fixture.CreateOptions(testStore));
var results = db.Customers
.Where(c => c.CompanyName.StartsWith("A"))
.OrderByDescending(c => c.CustomerID)
.ToList();
Assert.Equal(4, results.Count);
Assert.Equal("AROUT", results[0].CustomerID);
Assert.Equal("ANTON", results[1].CustomerID);
Assert.Equal("ANATR", results[2].CustomerID);
Assert.Equal("ALFKI", results[3].CustomerID);
Assert.Equal("(171) 555-6750", results[0].Fax);
Assert.Null(results[1].Fax);
Assert.Equal("(5) 555-3745", results[2].Fax);
Assert.Equal("030-0076545", results[3].Fax);
}
[ConditionalFact]
public void Can_enumerate_entity_set()
{
using var testStore = SqlServerTestStore.GetNorthwindStore();
using var db = new NorthwindContext(Fixture.CreateOptions(testStore));
var results = new List<Customer>();
foreach (var item in db.Customers)
{
results.Add(item);
}
Assert.Equal(91, results.Count);
Assert.Equal("ALFKI", results[0].CustomerID);
Assert.Equal("Alfreds Futterkiste", results[0].CompanyName);
}
[ConditionalFact]
public async Task Can_save_changes()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
using (var db = new BloggingContext(options))
{
await CreateBlogDatabaseAsync<Blog>(db);
}
Fixture.TestSqlLoggerFactory.Clear();
using (var db = new BloggingContext(options))
{
var toUpdate = db.Blogs.Single(b => b.Name == "Blog1");
toUpdate.Name = "Blog is Updated";
var updatedId = toUpdate.Id;
var toDelete = db.Blogs.Single(b => b.Name == "Blog2");
toDelete.Name = "Blog to delete";
var deletedId = toDelete.Id;
db.Entry(toUpdate).State = EntityState.Modified;
db.Entry(toDelete).State = EntityState.Deleted;
var toAdd = db.Add(
new Blog
{
Name = "Blog to Insert",
George = true,
TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"),
NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777),
ToEat = 64,
OrNothing = 0.123456789,
Fuse = 777,
WayRound = 9876543210,
Away = 0.12345f,
AndChew = new byte[16]
}).Entity;
await db.SaveChangesAsync();
var addedId = toAdd.Id;
Assert.NotEqual(0, addedId);
Assert.Equal(EntityState.Unchanged, db.Entry(toUpdate).State);
Assert.Equal(EntityState.Unchanged, db.Entry(toAdd).State);
Assert.DoesNotContain(toDelete, db.ChangeTracker.Entries().Select(e => e.Entity));
Assert.Equal(3, Fixture.TestSqlLoggerFactory.SqlStatements.Count);
Assert.Contains("SELECT", Fixture.TestSqlLoggerFactory.SqlStatements[0]);
Assert.Contains("SELECT", Fixture.TestSqlLoggerFactory.SqlStatements[1]);
Assert.Contains("@p0='" + deletedId, Fixture.TestSqlLoggerFactory.SqlStatements[2]);
Assert.Contains("DELETE", Fixture.TestSqlLoggerFactory.SqlStatements[2]);
Assert.Contains("UPDATE", Fixture.TestSqlLoggerFactory.SqlStatements[2]);
Assert.Contains("INSERT", Fixture.TestSqlLoggerFactory.SqlStatements[2]);
var rows = await testDatabase.ExecuteScalarAsync<int>(
$"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {updatedId} AND Name = 'Blog is Updated'");
Assert.Equal(1, rows);
rows = await testDatabase.ExecuteScalarAsync<int>(
$"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {deletedId}");
Assert.Equal(0, rows);
rows = await testDatabase.ExecuteScalarAsync<int>(
$"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {addedId} AND Name = 'Blog to Insert'");
Assert.Equal(1, rows);
}
}
[ConditionalFact]
public async Task Can_save_changes_in_tracked_entities()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
int updatedId;
int deletedId;
int addedId;
var options = Fixture.CreateOptions(testDatabase);
using (var db = new BloggingContext(options))
{
var blogs = await CreateBlogDatabaseAsync<Blog>(db);
var toAdd = db.Blogs.Add(
new Blog
{
Name = "Blog to Insert",
George = true,
TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"),
NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777),
ToEat = 64,
OrNothing = 0.123456789,
Fuse = 777,
WayRound = 9876543210,
Away = 0.12345f,
AndChew = new byte[16]
}).Entity;
db.Entry(toAdd).State = EntityState.Detached;
var toUpdate = blogs[0];
toUpdate.Name = "Blog is Updated";
updatedId = toUpdate.Id;
var toDelete = blogs[1];
toDelete.Name = "Blog to delete";
deletedId = toDelete.Id;
db.Remove(toDelete);
db.Entry(toAdd).State = EntityState.Added;
await db.SaveChangesAsync();
addedId = toAdd.Id;
Assert.NotEqual(0, addedId);
Assert.Equal(EntityState.Unchanged, db.Entry(toUpdate).State);
Assert.Equal(EntityState.Unchanged, db.Entry(toAdd).State);
Assert.DoesNotContain(toDelete, db.ChangeTracker.Entries().Select(e => e.Entity));
}
using (var db = new BloggingContext(options))
{
var toUpdate = db.Blogs.Single(b => b.Id == updatedId);
Assert.Equal("Blog is Updated", toUpdate.Name);
Assert.Equal(0, db.Blogs.Count(b => b.Id == deletedId));
Assert.Equal("Blog to Insert", db.Blogs.Single(b => b.Id == addedId).Name);
}
}
[ConditionalFact]
public void Can_track_an_entity_with_more_than_10_properties()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
using (var context = new GameDbContext(options))
{
context.Database.EnsureCreatedResiliently();
context.Characters.Add(
new PlayerCharacter(
new Level { Game = new Game() }));
context.SaveChanges();
}
using (var context = new GameDbContext(options))
{
var character = context.Characters
.Include(c => c.Level.Game)
.OrderBy(c => c.Id)
.First();
Assert.NotNull(character.Game);
Assert.NotNull(character.Level);
Assert.NotNull(character.Level.Game);
}
}
[ConditionalFact]
public void Can_replace_identifying_FK_entity_with_many_to_many()
{
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
using (var context = new SomeDbContext(options))
{
context.Database.EnsureCreatedResiliently();
context.Add(new EntityA { EntityB = new EntityB { EntitiesC = { new EntityC() }, } });
context.SaveChanges();
}
var expectedCId = 0;
using (var context = new SomeDbContext(options))
{
var entityA = context.EntitiesA.Include(x => x.EntityB).ThenInclude(x => x.EntitiesC).OrderBy(x => x.Id).First();
entityA.EntityB = new EntityB { EntitiesC = { new EntityC() } };
context.SaveChanges();
expectedCId = entityA.EntityB.EntitiesC.Single().Id;
}
using (var context = new SomeDbContext(options))
{
var entityA = context.EntitiesA.Include(x => x.EntityB).ThenInclude(x => x.EntitiesC).OrderBy(x => x.Id).First();
Assert.Equal(expectedCId, entityA.EntityB.EntitiesC.Single().Id);
}
}
[ConditionalTheory]
[MemberData(
nameof(DataGenerator.GetCombinations),
new object[] { 0, 1, 2, 3, 4, 7 },
2,
MemberType = typeof(DataGenerator))]
public void Can_insert_entities_with_generated_PKs(int studentCount, int courseCount)
{
var students = new Student[]
{
new()
{
FirstMidName = "Carson",
LastName = "Alexander",
EnrollmentDate = DateTime.Parse("2019-09-01")
},
new()
{
FirstMidName = "Meredith",
LastName = "Alonso",
EnrollmentDate = DateTime.Parse("2017-09-01")
},
new()
{
FirstMidName = "Arturo",
LastName = "Anand",
EnrollmentDate = DateTime.Parse("2018-09-01")
},
new()
{
FirstMidName = "Gytis",
LastName = "Barzdukas",
EnrollmentDate = DateTime.Parse("2017-09-01")
},
new()
{
FirstMidName = "Yan",
LastName = "Li",
EnrollmentDate = DateTime.Parse("2017-09-01")
},
new()
{
FirstMidName = "Peggy",
LastName = "Justice",
EnrollmentDate = DateTime.Parse("2016-09-01")
},
new()
{
FirstMidName = "Laura",
LastName = "Norman",
EnrollmentDate = DateTime.Parse("2018-09-01")
},
new()
{
FirstMidName = "Nino",
LastName = "Olivetto",
EnrollmentDate = DateTime.Parse("2019-09-01")
}
};
var courses = new Course[]
{
new() { Title = "Chemistry", Credits = 3 },
new() { Title = "Microeconomics", Credits = 3 },
new() { Title = "Macroeconomics", Credits = 3 },
new() { Title = "Calculus", Credits = 4 },
new() { Title = "Trigonometry", Credits = 4 },
new() { Title = "Composition", Credits = 3 },
new() { Title = "Literature", Credits = 4 }
};
using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName);
var options = Fixture.CreateOptions(testDatabase);
var nextCourse = 0;
using (var context = new UniversityContext(options))
{
context.Database.EnsureCreatedResiliently();
for (var i = 0; i < studentCount; i++)
{
if (courseCount > 1)
{
students[i].Courses.Add(courses[nextCourse++]);
if(nextCourse >= courseCount)
{
nextCourse = 0;
}
students[i].Courses.Add(courses[nextCourse++]);
if (nextCourse >= courseCount)
{
nextCourse = 0;
}
}
context.Students.Add(students[i]);
}
for (var i = 0; i < courseCount; i++)
{
context.Courses.Add(courses[i]);
}
Assert.All(context.Enrollments.Local, e =>
{
var entry = context.Entry(e);
var student = e.Student;
var course = e.Course;
Assert.Equal(student.Id, e.StudentId);
Assert.Equal(course.Id, e.CourseId);
Assert.Equal(context.Entry(student).Property(e => e.Id).CurrentValue, entry.Property(e => e.StudentId).CurrentValue);
Assert.Equal(context.Entry(course).Property(e => e.Id).CurrentValue, entry.Property(e => e.CourseId).CurrentValue);
Assert.True(entry.Property(e => e.StudentId).IsTemporary);
Assert.True(entry.Property(e => e.CourseId).IsTemporary);
Assert.True(context.Entry(student).Property(e => e.Id).IsTemporary);
Assert.True(context.Entry(course).Property(e => e.Id).IsTemporary);
});
context.SaveChanges();
Assert.All(context.Enrollments.Local, e =>
{
var entry = context.Entry(e);
var student = e.Student;
var course = e.Course;
Assert.Equal(student.Id, e.StudentId);
Assert.Equal(course.Id, e.CourseId);
Assert.False(entry.Property(e => e.StudentId).IsTemporary);
Assert.False(entry.Property(e => e.CourseId).IsTemporary);
});
}
using (var context = new UniversityContext(options))
{
Assert.Equal(studentCount, context.Students.ToList().Count());