-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ULongConcurrency.cs
95 lines (76 loc) · 2.89 KB
/
ULongConcurrency.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
94
95
// 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 ULongConcurrency : Program
{
public void Run()
{
ConsoleWriteLines("Sample showing how to map rowversion to ulong...");
using (var context = new SampleDbContext())
{
CleanDatabase(context);
ConsoleWriteLines("Save a new entity...");
context.Add(
new Blog
{
Name = "OneUnicorn"
});
context.SaveChanges();
}
using (var context = new SampleDbContext())
{
ConsoleWriteLines("Read the entity back in one context...");
var blog = context.Set<Blog>().Single();
blog.Name = "TwoUnicorns";
using (var context2 = new SampleDbContext())
{
ConsoleWriteLines("Change the blog name and save in a different context...");
context2.Set<Blog>().Single().Name = "1unicorn2";
context2.SaveChanges();
}
try
{
ConsoleWriteLines("Change the blog name and save in the first context...");
context.SaveChanges();
}
catch (DbUpdateConcurrencyException e)
{
ConsoleWriteLines($"{e.GetType().FullName}: {e.Message}");
var databaseValues = context.Entry(blog).GetDatabaseValues();
context.Entry(blog).OriginalValues.SetValues(databaseValues);
ConsoleWriteLines("Refresh original values and save again...");
context.SaveChanges();
}
}
ConsoleWriteLines("Sample finished.");
}
public class SampleDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region ConfigureULongConcurrency
modelBuilder.Entity<Blog>()
.Property(e => e.Version)
.IsRowVersion()
.HasConversion<byte[]>();
#endregion
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted })
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=ULongConcurrency;Trusted_Connection=True;ConnectRetryCount=0")
.EnableSensitiveDataLogging();
}
#region ULongConcurrencyModel
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public ulong Version { get; set; }
}
#endregion
}