![](/img/trans.png)
[英]Why does the connection string in Startup interfere with EF Core migration?
[英]Ef core migration with different startup project
我有一個項目,我的 Azure 函數將作為 API 工作。然后我有一個單獨的“核心”項目,包括我的 efcore、dbcontext 和模型。
我在核心項目中添加了一個配置器 class,如下所示:
public static IServiceCollection AddDatabaseContext(this IServiceCollection services, Action<DatabaseOptions> configureOptions)
{
services.Configure(configureOptions);
services.AddDbContextPool<SampleApiDbContext>((provider, options) =>
{
var dbOptions = provider.GetRequiredService<IOptionsMonitor<DatabaseOptions>>().CurrentValue;
options.UseSqlServer(dbOptions.ConnectionString, b=> b.MigrationsAssembly("Dymak.SampleLibraryApi.Admin"));
});
return services;
}
以及我在 api 項目中的啟動 class。
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
string sqlConnection = Environment.GetEnvironmentVariable("SqlConnectionString");
builder.Services.AddDatabaseContext(options =>
{
options.ConnectionString = sqlConnection;
});
}
}
供參考我的 dbcontext。
public class SampleApiDbContext : DbContext
{
public SampleApiDbContext(DbContextOptions<SampleApiDbContext> options) : base(options)
{
}
public SampleApiDbContext()
{
}
public DbSet<Category> Categories { get; set; } = null!;
public DbSet<Models.TagType> Types { get; set; } = null!;
public DbSet<Tag> Tags { get; set; } = null!;
}
任何時候我運行命令
dotnet ef --startup-project ..\Dymak.SampleLibraryApi migrations add Initial
我收到以下錯誤消息
Unable to create an object of type 'SampleApiDbContext'. For different patterns.......
我一直無法找到解決我的問題的方法,所以我希望這里有人知道。
您是否嘗試在 ef migrations add 命令中引用您的目標(核心)項目?
dotnet ef --project <project-where-you-have-dbcontext> --startup-project ..\Dymak.SampleLibraryApi migrations add Initial
似乎因為我正在使用 azure 函數,所以這是不可能的,因為 EntityFramework 遷移無法在 Azure Function 中自動發現我的遷移。
所以我必須創建一個單獨的 class,我在其中創建了一個 IDesignTime 工廠。 (在核心項目中)
public class SampleApiDbContextFactory : IDesignTimeDbContextFactory<SampleApiDbContext>
{
public SampleApiDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<SampleApiDbContext>();
optionsBuilder.UseSqlServer("random string");
return new SampleApiDbContext(optionsBuilder.Options);
}
}
它確實解決了我的一些問題,但似乎我無法讓它自動進行遷移。 但這仍然對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.