-
Notifications
You must be signed in to change notification settings - Fork 2k
/
CompositeValueObject.cs
93 lines (75 loc) · 2.64 KB
/
CompositeValueObject.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace EFModeling.ValueConversions;
public class CompositeValueObject : Program
{
public void Run()
{
ConsoleWriteLines("Sample showing value conversions for a composite value object...");
using (var context = new SampleDbContext())
{
CleanDatabase(context);
ConsoleWriteLines("Save a new entity...");
context.Add(new Order { Price = new Money(3.99m, Currency.UsDollars) });
context.SaveChanges();
}
using (var context = new SampleDbContext())
{
ConsoleWriteLines("Read the entity back...");
var order = context.Set<Order>().Single();
ConsoleWriteLines($"Order with price {order.Price.Amount} in {order.Price.Currency}.");
}
ConsoleWriteLines("Sample finished.");
}
public class SampleDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region ConfigureCompositeValueObject
modelBuilder.Entity<Order>()
.Property(e => e.Price)
.HasConversion(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
v => JsonSerializer.Deserialize<Money>(v, (JsonSerializerOptions)null));
#endregion
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted })
.UseSqlite("DataSource=test.db")
.EnableSensitiveDataLogging();
}
#region CompositeValueObjectModel
public class Order
{
public int Id { get; set; }
public Money Price { get; set; }
}
#endregion
#region CompositeValueObject
public readonly struct Money
{
[JsonConstructor]
public Money(decimal amount, Currency currency)
{
Amount = amount;
Currency = currency;
}
public override string ToString()
=> (Currency == Currency.UsDollars ? "$" : "£") + Amount;
public decimal Amount { get; }
public Currency Currency { get; }
}
public enum Currency
{
UsDollars,
PoundsSterling
}
#endregion
}