Resolving Common Issues with Code First Migrations in ASP.NET Core

I was working on a multi project solution and needed to do some code first migrations. It had been a while since I had done migrations and when running them, I noticed an error I hadn’t seen before.

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Object reference not set to an instance of an object.

This was a strange error, and after adding the -v switch to the dotnet ef migrations add test -v command, I could see that my startup was referencing a null configuration value. First problem solved!

Next up was the following error:

Your target project 'Aspnetcoreapp' doesn't match your migrations assembly 'Library'. Either change your target project or change your migrations assembly.

This error was occurring because the migrations assembly was not correctly set in my DbContext. By default, the migrations assembly is the assembly containing the DbContext. However, in my case, the DbContext was located in a separate assembly, and I needed to specify the correct migrations assembly.

The solution was to use the DbContextOptionsBuilder to set the migrations assembly. Specifically, I added the following line of code to my DbContext:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = _configuration.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly("Aspnetcoreapp"));
}


This line of code sets the migrations assembly to “Aspnetcoreapp”, which is the correct assembly for my project. By setting the migrations assembly correctly, I was able to resolve the error and continue with my code first migrations.

Example Code

Here is an example of the complete DbContext code:


using DAL.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace DAL
{
public partial class databaseContext : IdentityDbContext{private readonly IConfiguration _configuration;
    public databaseContext(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionString = _configuration.GetConnectionString("DefaultConnection");
        optionsBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly("Aspnetcoreapp"));
    }
}
}


I hope this helps! Feel free to reach out for any extra help!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *