-
Notifications
You must be signed in to change notification settings - Fork 0
/
StoreContext.cs
67 lines (56 loc) · 2.63 KB
/
StoreContext.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
using Microsoft.EntityFrameworkCore;
using System.Xml;
namespace GuitarShop;
public class StoreContext : DbContext
{
public DbSet<Guitar> Guitars { get; set; }
public DbSet<Musician> Musicians { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//This is just an example app, so we're hard-coding the connection string here.
//In a real app, do not hard code connection strings, or store it plain text in a config file
//Consider options like Azure Key Vault for storing secrets like connection strings
optionsBuilder.UseSqlServer(@"Server=.\;Database=GuitarShop;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//temporal tables
modelBuilder.Entity<Guitar>().ToTable("Guitars", x => x.IsTemporal(o => o.UseHistoryTable("GuitarLogs", "History")));
modelBuilder.Entity<Musician>().ToTable("Musicians", x => x.IsTemporal(o => o.UseHistoryTable("MusicianLogs", "History")));
ApplyColumnPrecisionAndDefaultsGlobally(modelBuilder);
base.OnModelCreating(modelBuilder);
}
/// <summary>
/// Set sql server column precisions if not specifically specified in code attributes - decimals and varchar
/// </summary>
/// <param name="modelBuilder"></param>
private static void ApplyColumnPrecisionAndDefaultsGlobally(ModelBuilder modelBuilder)
{
//decimals
var decimalProperties = modelBuilder.Model.GetEntityTypes().SelectMany(t => t.GetProperties()).Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?));
foreach (var property in decimalProperties)
{
property.SetColumnType("decimal(18, 3)");
}
//strings
var stringProperties = modelBuilder.Model.GetEntityTypes().SelectMany(t => t.GetProperties()).Where(p => p.ClrType == typeof(string));
foreach (var property in stringProperties)
{
if (property.GetMaxLength() == null)
{
//don't use MAX for varchar, it's not performant
property.SetMaxLength(4000);
}
}
//temporal table settings - schema and time range fields
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (entityType.IsTemporal())
{
entityType.SetHistoryTableSchema("History");
entityType.SetPeriodStartPropertyName("ValidFrom");
entityType.SetPeriodEndPropertyName("ValidTo");
}
}
}
}