-
Notifications
You must be signed in to change notification settings - Fork 2k
/
EncryptPropertyValues.cs
65 lines (52 loc) · 2.08 KB
/
EncryptPropertyValues.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
// 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 Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace EFModeling.ValueConversions;
public class EncryptPropertyValues : Program
{
public void Run()
{
ConsoleWriteLines("Sample showing value conversions for encrypting property values...");
using (var context = new SampleDbContext())
{
CleanDatabase(context);
ConsoleWriteLines("Save a new entity...");
context.Add(new User { Name = "arthur", Password = "password" });
context.SaveChanges();
}
using (var context = new SampleDbContext())
{
ConsoleWriteLines("Read the entity back...");
var user = context.Set<User>().Single();
ConsoleWriteLines($"User {user.Name} has password '{user.Password}'");
}
ConsoleWriteLines("Sample finished.");
}
public class SampleDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region ConfigureEncryptPropertyValues
modelBuilder.Entity<User>().Property(e => e.Password).HasConversion(
v => new string(v.Reverse().ToArray()),
v => new string(v.Reverse().ToArray()));
#endregion
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted })
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EncryptPropertyValues;Trusted_Connection=True;ConnectRetryCount=0")
.EnableSensitiveDataLogging();
}
#region EncryptPropertyValuesModel
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
#endregion
}