Snippets Angular ASP.NET Core Tutorial Part 1

Snippets Angular ASP.NET Core Tutorial Part 1

Summary:

Code snippets for the YouTube video ” Angular ASP.NET Core Minimal APIs Tutorial (pt. 1 – back end)”. AppDbContext.cs appsettings.json Add DbContext to DI PostsEndpoints.cs Program.cs

Code snippets for the YouTube video ” Angular ASP.NET Core Minimal APIs Tutorial (pt. 1 – back end)”.

AppDbContext.cs

using Microsoft.EntityFrameworkCore;
using Server.Data.Models;

namespace Server.Data;

public class AppDbContext : DbContext
{
    // We use => (expression-bodied members) to avoid nullable reference types errors.
    // Source: https://docs.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types#dbcontext-and-dbset.
    public DbSet<Post> Posts => Set<Post>();

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Call the base version of this method (in DbContext) as well, else we sometimes get an error later on.
        base.OnModelCreating(modelBuilder);

        var postsToSeed = new Post[6];

        for (int i = 1; i < 7; i++)
        {
            postsToSeed[i - 1] = new()
            {
                Id = i,
                Title = $"Post {i}",
                Content = $"Content of post {i}",
                Published = true
            };
        }

        modelBuilder.Entity<Post>().HasData(postsToSeed);
    }
}

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=./Data/AppDb.db"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Add DbContext to DI


builder.Services.AddDbContext<AppDbContext>(dbContextOptionsBuilder => 
    dbContextOptionsBuilder.UseSqlite(builder.Configuration["ConnectionStrings:DefaultConnection"]));

PostsEndpoints.cs

using Microsoft.EntityFrameworkCore;
using Server.Data;
using Server.Data.Models;

namespace Server;

public static class PostsEndpoints
{
    // Extends WebApplication.
    public static void MapPostsEndpoints(this WebApplication app)
    {
        app.MapGet("/posts", async (AppDbContext dbContext) =>
        {
            List<Post> allPosts = await dbContext.Posts.ToListAsync();

            return Results.Ok(allPosts);
        });

        app.MapGet("/posts/{Id}", async (int Id, AppDbContext dbContext) =>
        {
            Post? post = await dbContext.Posts.FindAsync(Id);

            if (post != null)
            {
                return Results.Ok(post);
            }
            else
            {
                return Results.NotFound();
            }
        });

        app.MapPost("/posts", async (PostCreateUpdateDTO postToCreateDTO, AppDbContext dbContext) =>
        {
            // Let EF Core auto-increment the ID.
            Post PostToCreate = new()
            {
                Id = 0,
                Title = postToCreateDTO.Title,
                Content = postToCreateDTO.Content,
                Published = postToCreateDTO.Published
            };

            dbContext.Posts.Add(PostToCreate);

            bool success = await dbContext.SaveChangesAsync() > 0;

            if (success)
            {
                return Results.Created($"/posts/{PostToCreate.Id}", postToCreate);
            }
            else
            {
                // 500 = internal server error.
                return Results.StatusCode(500);
            }
        });

        app.MapPut("/posts/{Id}", async (int Id, PostCreateUpdateDTO updatedPostDTO, AppDbContext dbContext) =>
        {
            var postToUpdate = await dbContext.Posts.FindAsync(Id);

            if (postToUpdate != null)
            {
                postToUpdate.Title = updatedPostDTO.Title;
                postToUpdate.Content = updatedPostDTO.Content;
                postToUpdate.Published = updatedPostDTO.Published;

                bool success = await dbContext.SaveChangesAsync() > 0;

                if (success)
                {
                    return Results.Ok(postToUpdate);
                }
                else
                {
                    // 500 = internal server error.
                    return Results.StatusCode(500);
                }
            }
            else
            {
                return Results.NotFound();
            }
        });

        app.MapDelete("/posts/{Id}", async (int Id, AppDbContext dbContext) =>
        {
            Post? postToDelete = await dbContext.Posts.FindAsync(Id);

            if (postToDelete != null)
            {
                dbContext.Posts.Remove(postToDelete);

                bool success = await dbContext.SaveChangesAsync() > 0;

                if (success)
                {
                    return Results.NoContent();
                }
                else
                {
                    // 500 = internal server error.
                    return Results.StatusCode(500);
                }
            }
            else
            {
                return Results.NotFound();
            }
        });
    }
}

Program.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Server;
using Server.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddDbContext<AppDbContext>(dbContextOptionsBuilder =>
    dbContextOptionsBuilder.UseSqlite(builder.Configuration["ConnectionStrings:DefaultConnection"]));

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(swaggerGenOptions =>
{
    swaggerGenOptions.SwaggerDoc("v1", new OpenApiInfo { Title = "Angular ASP.NET Core Tutorial Web API", Version = "v1" });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI(swaggerUIOptions =>
{
    swaggerUIOptions.DocumentTitle = "Angular ASP.NET Core Tutorial Web API";
    swaggerUIOptions.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API serving a simple Post model.");
    swaggerUIOptions.RoutePrefix = string.Empty;
});

app.UseHttpsRedirection();

app.MapPostsEndpoints();

app.Run();
Join the discussion

Articles