-
Notifications
You must be signed in to change notification settings - Fork 2k
/
PrimitiveCollection.cs
81 lines (65 loc) · 2.69 KB
/
PrimitiveCollection.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
// 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.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace EFModeling.ValueConversions;
public class PrimitiveCollection : Program
{
public void Run()
{
ConsoleWriteLines("Sample showing value conversions for a collections of primitive values...");
using (var context = new SampleDbContext())
{
CleanDatabase(context);
ConsoleWriteLines("Save a new entity...");
context.Add(new Post { Tags = new List<string> { "EF Core", "Unicorns", "Donkeys" } });
context.SaveChanges();
}
using (var context = new SampleDbContext())
{
ConsoleWriteLines("Read the entity back...");
var post = context.Set<Post>().Single();
ConsoleWriteLines($"Post with tags {string.Join(", ", post.Tags)}.");
ConsoleWriteLines("Changing the value object and saving again");
post.Tags.Add("ASP.NET Core");
context.SaveChanges();
}
ConsoleWriteLines("Sample finished.");
}
public class SampleDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region ConfigurePrimitiveCollection
modelBuilder.Entity<Post>()
.Property(e => e.Tags)
.HasConversion(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
v => JsonSerializer.Deserialize<List<string>>(v, (JsonSerializerOptions)null),
new ValueComparer<ICollection<string>>(
(c1, c2) => c1.SequenceEqual(c2),
c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
c => (ICollection<string>)c.ToList()));
#endregion
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted })
.UseSqlite("DataSource=test.db")
.EnableSensitiveDataLogging();
}
#region PrimitiveCollectionModel
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Contents { get; set; }
public ICollection<string> Tags { get; set; }
}
#endregion
}