-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathProjectionSnippets.cs
More file actions
73 lines (60 loc) · 2 KB
/
ProjectionSnippets.cs
File metadata and controls
73 lines (60 loc) · 2 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using StringGraphType = GraphQL.Types.StringGraphType;
class ProjectionSnippets
{
#region ProjectionEntity
public class Order
{
// Primary key
public int Id { get; set; }
// Foreign key
public int CustomerId { get; set; }
// Navigation property
public Customer Customer { get; set; } = null!;
public string OrderNumber { get; set; } = null!;
public decimal TotalAmount { get; set; }
public string InternalNotes { get; set; } = null!;
}
#endregion
#region ProjectionExpression
static void ProjectionExample(MyDbContext context) =>
_ = context.Orders.Select(o => new Order
{
// Requested (and primary key)
Id = o.Id,
// Automatically included (foreign key)
CustomerId = o.CustomerId,
// Requested
OrderNumber = o.OrderNumber
});
#endregion
#region ProjectionCustomResolver
public class OrderGraph :
EfObjectGraphType<MyDbContext, Order>
{
public OrderGraph(IEfGraphQLService<MyDbContext> graphQlService) :
base(graphQlService) =>
// Custom field that uses the foreign key
Field<StringGraphType>("customerName")
.ResolveAsync(async context =>
{
var data = ResolveDbContext(context);
// CustomerId is available even though it wasn't in the GraphQL query
return await data.Customers
.Where(c => c.Id == context.Source.CustomerId)
.Select(c => c.Name)
.SingleAsync();
});
}
#endregion
public class MyDbContext :
DbContext
{
public DbSet<Order> Orders { get; set; } = null!;
public DbSet<Customer> Customers { get; set; } = null!;
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = null!;
}
}