Reputation: 3541
I have a project with just one class library. I'm now trying to generate a migration in the class library.
Herer is my DbContext
:
public class DatabaseContext : DbContext, IDatabaseContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{ }
public DbSet<Security> Services { get; set; }
public DatabaseFacade DatabaseAccessor => this.Database;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.EnableSensitiveDataLogging();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("dbo");
modelBuilder.Entity<Security>().HasNoKey();
base.OnModelCreating(modelBuilder);
}
}
When I run the command
dotnet ef migrations add InitialCreate --project SecurityAttribute
I get the following error:
Unable to create an object of type 'DatabaseContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
My IServiceCollections
looks like this:
public static IServiceCollection AddServiceAndRoleSecurity(this IServiceCollection services)
{
services.AddTransient<ISecurityService, SecurityService>();
services.AddMemoryCache();
services.AddTransient<ISecurityRepository, SecurityRepository>();
services.AddDbContext<IDatabaseContext, DatabaseContext>(options => options.UseSqlServer(
@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=SecurityAttribute;Integrated Security=SSPI;",
sqlServerOptions => sqlServerOptions.CommandTimeout(10 * 60)
));
services.AddTransient<IDatabaseContextFactory, DatabaseContextFactory>();
return services;
}
public static IHost CreateDatabase(this IHost host)
{
using (var scope = host.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<IDatabaseContext>();
var migrations = db.DatabaseAccessor.GetPendingMigrations();
if (migrations.Any())
db.DatabaseAccessor.Migrate();
}
return host;
}
My class library will be used as a nuget package. That's why I only have a class library.
Upvotes: 1
Views: 2509
Reputation: 841
I think the best solution is to create a test project with Startup.cs. Where in configure services you register your DbContext
and use this project for managing migrations.
To specify where migrations should be added you can add this option to DbContext
options:
options.UseSqlServer(
connectionString,
x => x.MigrationsAssembly("MyLib.Migrations"));
where MyLib.Migrations
- name of the assembly where to store migrations
Upvotes: 3
Reputation: 1
Are you running your command (dotnet ef migrations add InitialCreate --project SecurityAttribute) in the package manager console? If so do you have the default project set correctly in the package manager console drop down? Is the start up project for the solution set to be the one with the Startup.cs?
Upvotes: -1