-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathJsonColumnsSample.cs
More file actions
325 lines (260 loc) · 10.9 KB
/
JsonColumnsSample.cs
File metadata and controls
325 lines (260 loc) · 10.9 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
using System.Net;
namespace NewInEfCore8;
public static class JsonColumnsSample
{
public static Task Json_columns_with_TPH()
{
PrintSampleName();
return JsonColumnsTest<JsonBlogsContext>();
}
public static Task Json_columns_with_TPH_on_SQLite()
{
PrintSampleName();
return JsonColumnsTest<JsonBlogsContextSqlite>();
}
private static async Task JsonColumnsTest<TContext>()
where TContext : BlogsContext, new()
{
await using var context = new TContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();
await context.Seed();
context.LoggingEnabled = true;
context.ChangeTracker.Clear();
#region CollectionIndexPredicate
var cutoff = DateOnly.FromDateTime(DateTime.UtcNow - TimeSpan.FromDays(365));
var updatedPosts = await context.Posts
.Where(
p => p.Metadata!.Updates[0].UpdatedOn < cutoff
&& p.Metadata!.Updates[1].UpdatedOn < cutoff)
.ToListAsync();
#endregion
Console.WriteLine();
foreach (var post in updatedPosts)
{
Console.WriteLine($"Post '{post.Title.Substring(0, 10)}...' with updates on {post.Metadata!.Updates[0].UpdatedOn} and {post.Metadata.Updates[1].UpdatedOn}.");
}
Console.WriteLine();
#region CollectionIndexNestedPredicate
var twentyTen = DateOnly.FromDateTime(new DateTime(2010, 1, 1));
var postsWithFirstCommit = await context.Posts
.Where(
p => p.Metadata!.Updates[0].UpdatedOn > twentyTen
&& p.Metadata!.Updates[0].Commits[0].Comment == "Commit #1")
.ToListAsync();
#endregion
Console.WriteLine();
foreach (var post in postsWithFirstCommit)
{
Console.WriteLine($"Post '{post.Title.Substring(0, 10)}...' with first commit on {post.Metadata!.Updates[0].Commits[0].CommittedOn}.");
}
Console.WriteLine();
#region CollectionIndexProjectionNullable
var postsAndRecentUpdatesNullable = await context.Posts
.Select(p => new
{
p.Title,
LatestUpdate = (DateOnly?)p.Metadata!.Updates[0].UpdatedOn,
SecondLatestUpdate = (DateOnly?)p.Metadata.Updates[1].UpdatedOn
})
.ToListAsync();
#endregion
Console.WriteLine();
foreach (var post in postsAndRecentUpdatesNullable)
{
Console.WriteLine($"Post '{post.Title.Substring(0, 10)}...' with updates on {post.LatestUpdate?.ToString() ?? "<none>"} and {post.SecondLatestUpdate?.ToString() ?? "<none>"}.");
}
Console.WriteLine();
#pragma warning disable CS8073
#region CollectionIndexProjection
var postsAndRecentUpdates = await context.Posts
.Where(p => p.Metadata!.Updates[0].UpdatedOn != null
&& p.Metadata!.Updates[1].UpdatedOn != null)
.Select(p => new
{
p.Title,
LatestUpdate = p.Metadata!.Updates[0].UpdatedOn,
SecondLatestUpdate = p.Metadata.Updates[1].UpdatedOn
})
.ToListAsync();
#endregion
#pragma warning restore CS8073
Console.WriteLine();
foreach (var post in postsAndRecentUpdates)
{
Console.WriteLine($"Post '{post.Title.Substring(0, 10)}...' with updates on {post.LatestUpdate} and {post.SecondLatestUpdate}.");
}
Console.WriteLine();
#region CollectionIndexNestedProjection
var postsAndFirstCommit = await context.Posts
.Select(p => new
{
p.Title,
CommitComment = (string?)p.Metadata!.Updates[0].Commits[0].Comment
})
.ToListAsync();
#endregion
Console.WriteLine();
foreach (var post in postsAndFirstCommit)
{
Console.WriteLine($"Post '{post.Title.Substring(0, 10)}...' with commit '{post.CommitComment?.ToString() ?? "<none>"}'.");
}
Console.WriteLine();
#region AuthorsInChigley
var authorsInChigley = await context.Authors
.Where(author => author.Contact.Address.City == "Chigley")
.ToListAsync();
#endregion
Console.WriteLine();
foreach (var author in authorsInChigley)
{
Console.WriteLine($"{author.Name} lives at '{author.Contact.Address.Street}' in Chigley.");
}
Console.WriteLine();
#region PostcodesInChigley
var postcodesInChigley = await context.Authors
.Where(author => author.Contact.Address.City == "Chigley")
.Select(author => author.Contact.Address.Postcode)
.ToListAsync();
#endregion
Console.WriteLine();
Console.WriteLine($"Postcodes in Chigley are '{string.Join("', '", postcodesInChigley)}'");
Console.WriteLine();
#region OrderedAddresses
var orderedAddresses = await context.Authors
.Where(
author => (author.Contact.Address.City == "Chigley"
&& author.Contact.Phone != null)
|| author.Name.StartsWith("D"))
.OrderBy(author => author.Contact.Phone)
.Select(
author => author.Name + " (" + author.Contact.Address.Street
+ ", " + author.Contact.Address.City
+ " " + author.Contact.Address.Postcode + ")")
.ToListAsync();
#endregion
Console.WriteLine();
foreach (var address in orderedAddresses)
{
Console.WriteLine(address);
}
Console.WriteLine();
var authorsInChigleyWithPosts = await context.Authors
.Where(
author => author.Contact.Address.City == "Chigley"
&& author.Posts.Count > 1)
.Include(author => author.Posts)
.ToListAsync();
Console.WriteLine();
foreach (var author in authorsInChigleyWithPosts)
{
Console.WriteLine($"{author.Name} has {author.Posts.Count} posts");
}
Console.WriteLine();
#region PostsWithViews
var postsWithViews = await context.Posts.Where(post => post.Metadata!.Views > 3000)
.AsNoTracking()
.Select(
post => new
{
post.Author!.Name, post.Metadata!.Views, Searches = post.Metadata.TopSearches, Commits = post.Metadata.Updates
})
.ToListAsync();
#endregion
Console.WriteLine();
foreach (var postWithViews in postsWithViews)
{
Console.WriteLine(
$"Post by {postWithViews.Name} with {postWithViews.Views} views had {postWithViews.Commits.Count} commits with {postWithViews.Searches.Sum(term => term.Count)} searches");
}
Console.WriteLine();
#region PostsWithSearchTerms
var searchTerms = new[] { "Search #2", "Search #3", "Search #5", "Search #8", "Search #13", "Search #21", "Search #34" };
var postsWithSearchTerms = await context.Posts
.Where(post => post.Metadata!.TopSearches.Any(s => searchTerms.Contains(s.Term)))
.ToListAsync();
#endregion
Console.WriteLine();
foreach (var postWithTerm in postsWithSearchTerms)
{
Console.WriteLine(
$"Post {postWithTerm.Id} with terms '{string.Join("', '", postWithTerm.Metadata!.TopSearches.Select(s => s.Term))}'");
}
Console.WriteLine();
context.ChangeTracker.Clear();
Console.WriteLine("Updating a 'Contact' JSON document...");
Console.WriteLine();
#region UpdateDocument
var jeremy = await context.Authors.SingleAsync(author => author.Name.StartsWith("Jeremy"));
jeremy.Contact = new() { Address = new("2 Riverside", "Trimbridge", "TB1 5ZS", "UK"), Phone = "01632 88346" };
await context.SaveChangesAsync();
#endregion
context.ChangeTracker.Clear();
Console.WriteLine("Updating an 'Address' inside the 'Contact' JSON document...");
Console.WriteLine();
#region UpdateSubDocument
var brice = await context.Authors.SingleAsync(author => author.Name.StartsWith("Brice"));
brice.Contact.Address = new("4 Riverside", "Trimbridge", "TB1 5ZS", "UK");
await context.SaveChangesAsync();
#endregion
context.ChangeTracker.Clear();
Console.WriteLine();
Console.WriteLine("Updating only 'Country' in a 'Contact' JSON document...");
Console.WriteLine();
#region UpdateProperty
var arthur = await context.Authors.SingleAsync(author => author.Name.StartsWith("Arthur"));
arthur.Contact.Address.Country = "United Kingdom";
await context.SaveChangesAsync();
#endregion
Console.WriteLine();
context.ChangeTracker.Clear();
var hackingPost = await context.Posts.SingleAsync(post => post.Title.StartsWith("Hacking"));
hackingPost.Metadata!.Updates.Add(new PostUpdate(IPAddress.Broadcast, DateOnly.FromDateTime(DateTime.UtcNow)) { UpdatedBy = "User" });
hackingPost.Metadata!.TopGeographies.Clear();
await context.SaveChangesAsync();
}
private static void PrintSampleName([CallerMemberName] string? methodName = null)
{
Console.WriteLine($">>>> Sample: {methodName}");
Console.WriteLine();
}
}
public abstract class JsonBlogsContextBase : BlogsContext
{
protected JsonBlogsContextBase(bool useSqlite = false)
: base(useSqlite)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>().OwnsOne(
author => author.Contact, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
ownedNavigationBuilder.OwnsOne(contactDetails => contactDetails.Address);
});
#region PostMetadataConfig
modelBuilder.Entity<Post>().OwnsOne(
post => post.Metadata, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
ownedNavigationBuilder.OwnsMany(metadata => metadata.TopSearches);
ownedNavigationBuilder.OwnsMany(metadata => metadata.TopGeographies);
ownedNavigationBuilder.OwnsMany(
metadata => metadata.Updates,
ownedOwnedNavigationBuilder => ownedOwnedNavigationBuilder.OwnsMany(update => update.Commits));
});
#endregion
base.OnModelCreating(modelBuilder);
}
}
public class JsonBlogsContext : JsonBlogsContextBase
{
}
public class JsonBlogsContextSqlite : JsonBlogsContextBase
{
public JsonBlogsContextSqlite()
: base(useSqlite: true)
{
}
}