Mason Turvey
Mason Turvey

Reputation: 325

Injecting an EF Context in ASP.NET Core app and using migrations

I am currently attempting to use an EF Core dbcontext with a cosmos db on .NET Core 2.2. My startup cs has a db context injection setup like this:

var configBuilder= new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");

IConfigurationRoot config = configBuilder.Build();

IConfigurationSection configSection = config.GetSection("CosmosSettings");

services.AddDbContext<PiServeDb>(options => options.UseCosmosSql(
    configSection["ServiceEndpoint"], configSection["AuthKey"], configSection["DatabaseName"]
));

With the cosmosdb config stuff in the appsettings.json file.

The DbContext is setup to allow a DbContextOptions like so:

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

    public DbSet<Device> Devices { get; set; }
}

and when trying to run an initial migration to update the database I am getting this error consistently:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Migrations.IMigrator'. This is often because no database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

I have configured the class to accept this in the constructor so I have no clue what I have done wrong. Is there anything wrong with my setup?

Upvotes: 1

Views: 613

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239440

CosmosDB is schema-less. As such, there's no concept of "migrations". If you add a new property, it just starts saving data for that new property. Granted, there are certain scenarios where you'd like to "migrate" - perhaps you renamed a prop. However, that is more a data migration. All the items in your container will need to be updated to move the data from the old member to the new member. EF Core does not currently support this type of scenario, so you'll need to come up with your own strategy to make such changes.

Long and short, you don't create migrations for a CosmosDB store, so that's likely why this doesn't work.

Upvotes: 2

Related Questions