-
Notifications
You must be signed in to change notification settings - Fork 2k
/
SimpleMaterializationSample.cs
86 lines (71 loc) · 2.5 KB
/
SimpleMaterializationSample.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
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace NewInEfCore7;
public static class SimpleMaterializationSample
{
public static async Task Simple_actions_on_entity_creation()
{
PrintSampleName();
await using (var context = new CustomerContext())
{
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();
await context.AddRangeAsync(
new Customer { Name = "Alice", PhoneNumber = "+1 515 555 0123" },
new Customer { Name = "Mac", PhoneNumber = "+1 515 555 0124" });
await context.SaveChangesAsync();
}
#region QueryCustomer
await using (var context = new CustomerContext())
{
var customer = await context.Customers.SingleAsync(e => e.Name == "Alice");
Console.WriteLine($"Customer '{customer.Name}' was retrieved at '{customer.Retrieved.ToLocalTime()}'");
}
#endregion
}
private static void PrintSampleName([CallerMemberName] string? methodName = null)
{
Console.WriteLine($">>>> Sample: {methodName}");
Console.WriteLine();
}
#region CustomerContext
public class CustomerContext : DbContext
{
private static readonly SetRetrievedInterceptor _setRetrievedInterceptor = new();
public DbSet<Customer> Customers
=> Set<Customer>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.AddInterceptors(_setRetrievedInterceptor)
.UseSqlite("Data Source = customers.db");
}
#endregion
#region SetRetrievedInterceptor
public class SetRetrievedInterceptor : IMaterializationInterceptor
{
public object InitializedInstance(MaterializationInterceptionData materializationData, object instance)
{
if (instance is IHasRetrieved hasRetrieved)
{
hasRetrieved.Retrieved = DateTime.UtcNow;
}
return instance;
}
}
#endregion
#region IHasRetrieved
public interface IHasRetrieved
{
DateTime Retrieved { get; set; }
}
#endregion
#region Customer
public class Customer : IHasRetrieved
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public string? PhoneNumber { get; set; }
[NotMapped]
public DateTime Retrieved { get; set; }
}
#endregion
}