-
-
Notifications
You must be signed in to change notification settings - Fork 725
/
UseDbContextAttribute.cs
44 lines (39 loc) · 1.49 KB
/
UseDbContextAttribute.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
using System;
using System.Reflection;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
using Microsoft.EntityFrameworkCore;
using static HotChocolate.Data.Properties.EntityFrameworkResources;
namespace HotChocolate.Data
{
public class UseDbContextAttribute : ObjectFieldDescriptorAttribute
{
private static readonly MethodInfo _useDbContext =
typeof(EntityFrameworkObjectFieldDescriptorExtensions)
.GetMethod(
nameof(EntityFrameworkObjectFieldDescriptorExtensions.UseDbContext),
BindingFlags.Public | BindingFlags.Static)!;
private readonly Type _dbContext;
public UseDbContextAttribute(Type dbContext)
{
_dbContext = dbContext;
}
public override void OnConfigure(
IDescriptorContext context,
IObjectFieldDescriptor descriptor,
MemberInfo member)
{
if (!typeof(DbContext).IsAssignableFrom(_dbContext))
{
throw new SchemaException(
SchemaErrorBuilder.New()
.SetMessage(
UseDbContextAttribute_OnConfigure_NoDbContextType,
_dbContext.FullName ?? _dbContext.Name)
.SetExtension(nameof(member), member)
.Build());
}
_useDbContext.MakeGenericMethod(_dbContext).Invoke(null, new object?[] { descriptor });
}
}
}