简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM