-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathMetadataProvider.cs
More file actions
52 lines (40 loc) · 1.74 KB
/
MetadataProvider.cs
File metadata and controls
52 lines (40 loc) · 1.74 KB
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
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using PhenX.EntityFrameworkCore.BulkInsert.Abstractions;
namespace PhenX.EntityFrameworkCore.BulkInsert.Metadata;
internal sealed class MetadataProvider
{
private readonly Dictionary<Type, Dictionary<Type, TableMetadata>> _tablesPerContext = new();
public TableMetadata GetTableInfo<T>(DbContext context)
{
lock (_tablesPerContext)
{
var type = context.GetType();
if (!_tablesPerContext.TryGetValue(type, out var tables))
{
tables = new Dictionary<Type, TableMetadata>();
_tablesPerContext[type] = tables;
}
var modelType = typeof(T);
if (tables.TryGetValue(modelType, out var table))
{
return table;
}
var entityType = context.Model.FindEntityType(modelType);
if (entityType == null)
{
throw new InvalidOperationException($"The type '{modelType.FullName}' is not part of the model for the current context.");
}
// Filter out entities without an associated table
// See also https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types
if (entityType.GetTableName() is null)
{
throw new InvalidOperationException($"The type '{modelType.FullName}' is not mapped to a table in the database or is keyless.");
}
var provider = context.GetService<IBulkInsertProvider>();
var tableMetadata = new TableMetadata(entityType, provider.SqlDialect);
tables[modelType] = tableMetadata;
return tableMetadata;
}
}
}