-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
80 lines (68 loc) · 2.55 KB
/
Program.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
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace EFTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Setup...");
using (var context = new MyDbContext(useLazyLoading: false))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var parent = new Parent
{
Child = new ConcreteChild
{
GrandChildren = new List<GrandChild>
{
new GrandChild()
}
}
};
context.Parents.Add(parent);
context.SaveChanges();
}
Console.WriteLine($"Eagerly loading GrandChild entities fails (lazy loading ENABLED, no tracking)");
try
{
using (var context = new MyDbContext(useLazyLoading: true))
{
var results = context.Parents
.AsNoTracking()
.Include(x => x.Child.GrandChildren)
.ToList();
var child = results.Single().Child;
// Exception is thrown when accessing child.GrandChildren
Console.WriteLine($"GrandChildren.Count: {child.GrandChildren.Count}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
Console.WriteLine();
Console.WriteLine("----------------------------------------------");
Console.WriteLine();
Console.WriteLine($"Eagerly loading too many GrandChild entities (lazy loading DISABLED, no tracking)");
using (var context = new MyDbContext(useLazyLoading: false))
{
var results = context.Parents
.AsNoTracking()
.Include(x => x.Child.GrandChildren)
.Select(parent => new
{
Parent = parent,
Child = parent.Child
})
.ToList();
var child = results.Single().Child;
Console.WriteLine($"GrandChildren.Count expected: 1");
Console.WriteLine($"GrandChildren.Count actual: {child.GrandChildren.Count}");
}
}
}
}