-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathDbContextExtensions.cs
More file actions
54 lines (46 loc) · 1.92 KB
/
DbContextExtensions.cs
File metadata and controls
54 lines (46 loc) · 1.92 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
53
54
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace TestBuildingBlocks;
public static class DbContextExtensions
{
public static void AddInRange(this DbContext dbContext, params object[] entities)
{
dbContext.AddRange(entities);
}
public static async Task ClearTableAsync<TEntity>(this DbContext dbContext)
where TEntity : class
{
await dbContext.ClearTablesAsync(typeof(TEntity));
}
public static async Task ClearTablesAsync<TEntity1, TEntity2>(this DbContext dbContext)
where TEntity1 : class
where TEntity2 : class
{
await dbContext.ClearTablesAsync(typeof(TEntity1), typeof(TEntity2));
}
private static async Task ClearTablesAsync(this DbContext dbContext, params Type[] modelTypes)
{
foreach (Type modelType in modelTypes)
{
IEntityType? entityType = dbContext.Model.FindEntityType(modelType);
if (entityType == null)
{
throw new InvalidOperationException($"Table for '{modelType.Name}' not found.");
}
string? tableName = entityType.GetTableName();
if (tableName == null)
{
// There is no table for the specified abstract base type when using TablePerConcreteType inheritance.
IEnumerable<IEntityType> derivedTypes = entityType.GetConcreteDerivedTypesInclusive();
await dbContext.ClearTablesAsync(derivedTypes.Select(derivedType => derivedType.ClrType).ToArray());
}
else
{
#pragma warning disable EF1002 // Risk of vulnerability to SQL injection.
// Justification: Table names cannot be parameterized.
await dbContext.Database.ExecuteSqlRawAsync($"DELETE FROM \"{tableName}\"");
#pragma warning restore EF1002 // Risk of vulnerability to SQL injection.
}
}
}
}