-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathProgram.cs
More file actions
105 lines (87 loc) · 2.71 KB
/
Program.cs
File metadata and controls
105 lines (87 loc) · 2.71 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System.Diagnostics;
using GettingStarted.Data;
using GettingStarted.Definitions;
using GettingStarted.Models;
using JsonApiDotNetCore.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<SampleDbContext>(options =>
{
options.UseSqlite("Data Source=SampleDb.db;Pooling=False");
SetDbContextDebugOptions(options);
});
builder.Services.AddJsonApi<SampleDbContext>(options =>
{
options.Namespace = "api";
options.UseRelativeLinks = true;
options.IncludeTotalResourceCount = true;
#if DEBUG
options.IncludeExceptionStackTraceInErrors = true;
options.IncludeRequestBodyInErrors = true;
options.SerializerOptions.WriteIndented = true;
#endif
});
builder.Services.AddResourceDefinition<PersonDefinition>();
WebApplication app = builder.Build();
// Configure the HTTP request pipeline.
app.UseRouting();
app.UseJsonApi();
app.MapControllers();
await CreateDatabaseAsync(app.Services);
await app.RunAsync();
[Conditional("DEBUG")]
static void SetDbContextDebugOptions(DbContextOptionsBuilder options)
{
options.EnableDetailedErrors();
options.EnableSensitiveDataLogging();
options.ConfigureWarnings(builder => builder.Ignore(CoreEventId.SensitiveDataLoggingEnabledWarning));
}
static async Task CreateDatabaseAsync(IServiceProvider serviceProvider)
{
await using AsyncServiceScope scope = serviceProvider.CreateAsyncScope();
var dbContext = scope.ServiceProvider.GetRequiredService<SampleDbContext>();
await dbContext.Database.EnsureDeletedAsync();
await dbContext.Database.EnsureCreatedAsync();
await CreateSampleDataAsync(dbContext);
}
static async Task CreateSampleDataAsync(SampleDbContext dbContext)
{
// Note: The generate-examples.ps1 script (to create example requests in documentation) depends on these.
dbContext.Books.AddRange(new Book
{
Title = "Frankenstein",
PublishYear = 1818,
Author = new Person
{
Name = "Mary Shelley",
House = new BigHouse
{
FloorCount = 3
}
}
}, new Book
{
Title = "Robinson Crusoe",
PublishYear = 1719,
Author = new Person
{
Name = "Daniel Defoe",
House = new TinyHouse()
}
}, new Book
{
Title = "Gulliver's Travels",
PublishYear = 1726,
Author = new Person
{
Name = "Jonathan Swift",
House = new BigHouse
{
FloorCount = 4
}
}
});
await dbContext.SaveChangesAsync();
}