Tags: .NET, Back End, C#, Entity Framework, Front End, Full Stack, Javascript, React, REST
Table of Contents
- Introduction
- Install Packages
- Set Up a DbContext
- Specify a Database Type
- Create a Controller with CRUD Actions
- Add Seed Data
- Add API Documentation with Swagger
- Conclusion
- Comments
This is a continuation from the previous part, which can be found here. In this part, we will set up an Entity Framework DbContext
, create a class for our model, create a controller with CRUD actions using Entity Framework, and add Swagger API docs. The follow up post will be about adding CRUD functionality to the front end UI.
- Install the following Nuget packages.
- Microsoft.EntityFrameworkCore, Version=3.1.7
- Microsoft.EntityFrameworkCore.InMemory, Version=3.1.7
- Swashbuckle.AspNetCore, Version=5.5.1
- Create a
Notes
class in the Models folder.
public class Note
{
public Guid NoteId { get; set; }
public DateTime CreatedDate { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
- Create a
WebAppContext
class in the Models folder.
public class WebAppContext : DbContext
{
public DbSet<Note> Notes { get; set; }
public WebAppContext(DbContextOptions<WebAppContext> options)
: base(options)
{
}
}
- Modify
ConfigureServices
inStartup
as follows
public void ConfigureServices(IServiceCollection services)
{
...
// Use an Entity Framework in memory database for simplicity
services.AddDbContext<WebAppContext>(options => options.UseInMemoryDatabase("WebAppContext"));
}
- Right click on the Controllers folder > Add > Controller > API Controller with actins, using Entity Framework.
- Select
Note
for Model class. - Select
WebAppContext
for Data context class. - Click Add.
NotesController
should be created
- Add the following to
WebAppContext
.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Note>().HasData(new[] {
new Note {
NoteId = Guid.NewGuid(),
CreatedDate = DateTime.UtcNow,
Title = "Note 1",
Content = "Note 1 content here"
},
new Note {
NoteId = Guid.NewGuid(),
CreatedDate = DateTime.UtcNow.AddDays(-1),
Title = "Note 2",
Content = "Note 2 content here"
}
});
}
- Add the following to
NotesController
's default constructor.
public NotesController(WebAppContext context)
{
...
// Seed data
_context.Database.EnsureCreated();
}
-
Right click on the WebApp project > Properties > Build.
-
Add
;1591
to Suppress warnings. -
Check the box for XML documentation file.
-
Modify
ConfigureServices
inStartup
as follows.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Notes API",
Description = "A simple example ASP.NET Core Web API",
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}
- Modify
Configure
inStartup
as follows.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
- Add XML comments to
NotesController
.
/// <summary>
/// GET: api/Notes
/// </summary>
/// <remarks>
/// Remarks here
/// </remarks>
/// <returns></returns>
/// <response code="200">Returns list of notes</response>
[HttpGet]
public async Task<ActionResult<IEnumerable<Note>>> GetNotes()
...
-
Run the project (start debugging).
-
Navigate to /swagger. The following Swagger API docs should be shown.
The full example source code can be found here.
Reply to this tweet.