我有一个结构简单的.NET Core应用
// Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args)
.Build()
.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUnityServiceProvider()
.UseStartup<Startup>();
}
// Startup.cs
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
this.Configuration = configuration;
this.Environment = environment;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment Environment { get; }
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddControllersAsServices();
// This conditional is only flipped for testing purposes
// Migrations work perfectly fine for SqlLite
if (!this.Environment.IsDevelopment())
{
services
.AddDbContext<EstateContext>(opt => opt.UseSqlite(nameof(EstateContext)));
}
else
{
services
.AddEntityFrameworkSqlServer()
.AddDbContext<EstateContext>(opt => opt.UseSqlServer(
this.Configuration.GetConnectionString("DefaultConnection"),
sqlOptions => sqlOptions.MigrationsAssembly(
typeof(Property) // Where my .Data namespace lives
.Assembly
.FullName)));
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
if (this.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
public void ConfigureContainer(IUnityContainer container)
{
// This call currently does nothing
UnityConfig.ConfigureContainer(container);
}
}
该应用程序正常运行,但是当我尝试添加迁移时,出现错误消息
没有为类型'System.Collections.Generic.IEnumerable`1 [Microsoft.EntityFrameworkCore.DbContextOptions]'服务注册。”
如果我删除.UseUnityServiceProvider()
行,则迁移将按预期进行。如果我使用SqlLite而不是SqlServer,则可以使用.UseUnityServiceProvider()
运行迁移(大概是因为SqlLite不需要任何DbContextOptions或相关类)
作为参考,这是EstateContext的外观
public class EstateContext : DbContext
{
public EstateContext(DbContextOptions options)
: base(options)
{ }
public EstateContext(DbContextOptions<EstateContext> options)
: base(options)
{ }
protected override void OnModelCreating(ModelBuilder builder)
{
// Ignore the Mongo properties in the SQL DB
Assembly
.GetAssembly(typeof(MongoEntity))
.GetTypes()
.Where(t =>
t.IsClass &&
!t.IsAbstract &&
t.IsSubclassOf(typeof(MongoEntity)))
.ToList()
.ForEach(t =>
{
builder
.Entity(t)
.Ignore(nameof(MongoEntity.Id))
.Ignore(nameof(MongoEntity.Version));
});
}
public DbSet<Property> Properties { get; set; }
public DbSet<Tax> Taxes { get; set; }
public DbSet<HomeOwnerAssociation> Associations { get; set; }
}