Configure Many-to-Many Relationships using Fluent API in Entity Framework Core

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }
}
public class StudentCourse
{
    public int StudentId { get; set; }
    public Student Student { get; set; }

    public int CourseId { get; set; }
    public Course Course { get; set; }
}

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    public IList<StudentCourse> StudentCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }

    public IList<StudentCourse> StudentCourses { get; set; }
}
public class SchoolContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=.\\SQLEXPRESS;Database=EFCore-SchoolDB;Trusted_Connection=True");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<StudentCourse>().HasKey(sc => new { sc.StudentId, sc.CourseId });
    }
    
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }
    public DbSet<StudentCourse> StudentCourses { get; set; }
}

References
https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-core.aspx

Configure One-to-One Relationships using Fluent API in Entity Framework Core

using Microsoft.EntityFrameworkCore;

namespace BlazorApp1;

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql("Host=localhost;Database=testdb;Username=postgres;Password=12345");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .HasOne<StudentAddress>(s => s.Address)
            .WithOne(ad => ad.Student)
            .HasForeignKey<StudentAddress>(ad => ad.AddressOfStudentId);
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<StudentAddress> StudentAddresses { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public StudentAddress Address { get; set; }
}

public class StudentAddress
{
    public int StudentAddressId { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public int AddressOfStudentId { get; set; }
    public Student Student { get; set; }
}

References
https://www.entityframeworktutorial.net/efcore/configure-one-to-one-relationship-using-fluent-api-in-ef-core.aspx
https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

Configure One-to-Many Relationships using Fluent API in Entity Framework Core

 

using Microsoft.EntityFrameworkCore;

namespace BlazorApp1;

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql("Host=localhost;Database=testdb;Username=postgres;Password=12345");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .HasOne<Grade>(s => s.Grade)
            .WithMany(g => g.Students)
            .HasForeignKey(s => s.CurrentGradeId);
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Grade> Grades { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int CurrentGradeId { get; set; }
    public Grade Grade { get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }

    public ICollection<Student> Students { get; set; }
}

References
https://www.entityframeworktutorial.net/efcore/configure-one-to-many-relationship-using-fluent-api-in-ef-core.aspx
https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

Entity Framework Core tools reference – .NET Core CLI

Installing the tools

dotnet ef can be installed as either a global or local tool.

dotnet tool install --global dotnet-ef
dotnet new tool-manifest # if you are setting up this repo
dotnet tool install --local dotnet-ef

Before you can use the tools on a specific project, you’ll need to add the Microsoft.EntityFrameworkCore.Design package to it.

dotnet add package Microsoft.EntityFrameworkCore.Design

Update the tools

Use dotnet tool update --global dotnet-ef to update the global tools to the latest available version. If you have the tools installed locally in your project use dotnet tool update dotnet-ef. Install a specific version by appending --version <VERSION> to your command. See the Update section of the dotnet tool documentation for more details.

Usefull Commands

dotnet ef database drop

Deletes the database.

dotnet ef database update

Updates the database to the last migration or to a specified migration.

dotnet ef dbcontext info

Gets information about a DbContext type.

dotnet ef dbcontext list

Lists available DbContext types.

dotnet ef dbcontext optimize

Generates a compiled version of the model used by the DbContext. Added in EF Core 6.

dotnet ef dbcontext scaffold

Generates code for a DbContext and entity types for a database. In order for this command to generate an entity type, the database table must have a primary key.

dotnet ef dbcontext script

Generates a SQL script from the DbContext. Bypasses any migrations.

dotnet ef migrations add

Adds a new migration.

dotnet ef migrations bundle

Creates an executable to update the database.

dotnet ef migrations list

Lists available migrations.

dotnet ef migrations remove

Removes the last migration, rolling back the code changes that were done for the latest migration.

dotnet ef migrations script

Generates a SQL script from migrations.

Reverting a Migration

Suppose you changed your domain class and created the second migration named MySecondMigration using the add-migration command and applied this migration to the database using the Update command. But, for some reason, you want to revert the database to the previous state. In this case, use the update-database <migration name> command to revert the database to the specified previous migration snapshot.

dotnet ef database update MyFirstMigration

The above command will revert the database based on a migration named MyFirstMigration and remove all the changes applied for the second migration named MySecondMigration. This will also remove MySecondMigration entry from the __EFMigrationsHistory table in the database.

Note: This will not remove the migration files related to MySecondMigration. Use the remove commands to remove them from the project.

References
https://docs.microsoft.com/en-us/ef/core/cli/dotnet

Configure PostgreSQL Entity Framework for ASP.NET using Npgsql

Install Required Packages

dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore

Install dotnet-ef

Install it locally or globally.

Local

dotnet new tool-manifest # if you are setting up this repo
dotnet tool install --local dotnet-ef

Global

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design

Defining a DbContext

using Microsoft.EntityFrameworkCore;

namespace BlazorApp1;

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql("Host=localhost;Database=testdb;Username=postgres;Password=12345");
    }

    public DbSet<Person> People { get; set; }
}

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Create Migration

dotnet ef migrations add InitialCreate

Apply to Database

dotnet ef database update

or

dotnet ef database update InitialCreate
dotnet ef database update 20180904195021_InitialCreate --connection your_connection_string

Program.cs

builder.Services.AddDbContext<AppDbContext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("AppDbContext")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

References
https://www.npgsql.org/efcore/index.html
https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-6.0&tabs=visual-studio
https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations?view=aspnetcore-6.0
https://medium.com/executeautomation/asp-net-core-6-0-minimal-api-with-entity-framework-core-69d0c13ba9ab
https://docs.microsoft.com/en-us/ef/core/cli/dotnet