Dotnet
Authentication and Authorization - Registration Part 2

Add DB Context

PRO

I finished! On to the next chapter

Outline

Demo: Add Db Context

Add new class named:
  • ConduitContext
House cleaning
  • Make it public
  • Inherit from DbContext
  • Resolve Namespace for DbContext
  • Remove and Sort usings
Add Constructor
  • Include a parameter named "options" type DbContextOptions<ConduitContext>
  • Call the base constructor passing the "options" parameter
  • Leave the body of the constructor method empty
Add the following properties
  • Accounts
    • DbSet<Account>
  • People
    • DbSet<Person>
Override OnModelCreating Method

Implement the following configuration settings on Account:

  • Create a unique index name "IX_Accounts_Email_Unique"

Implement the following configuration settings on Person:

  • Prevent the Id value from being generated
  • Set a one-to-one relationship between Account & Person
  • Set a default value for the Image column
    • set it to "https://static.productionready.io/images/smiley-cyrus.jpg"

Here's the code the Conduit.Data.ConduitContext.cs file:

using Microsoft.EntityFrameworkCore;

namespace Conduit.Data
{
    public class ConduitContext : DbContext
    {
        public DbSet<Account> Accounts { get; set; }
        public DbSet<Person> People { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Account>(entity =>
            {
                entity
                    .HasIndex(e => e.Email, "IX_Accounts_Email_Unique")
                    .IsUnique();
            });

            modelBuilder.Entity<Person>(entity =>
            {
                entity
                    .Property(e => e.Id)
                    .ValueGeneratedNever();

                entity
                    .HasOne(d => d.Account)
                    .WithOne(p => p.Person)
                    .HasForeignKey<Person>(d => d.Id)
                    .OnDelete(DeleteBehavior.ClientSetNull);

                entity
                    .Property(e => e.Image)
                    .HasDefaultValue("'https://static.productionready.io/images/smiley-cyrus.jpg'");
            });

            base.OnModelCreating(modelBuilder);
        }

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