我有兩個項目。Entity Framework Core 2.0.0不同項目中的遷移
1).NetCore控制檯應用程序
- Microsoft.EntityFrameworkCore.Tools 2.0.0
- Microsoft.EntityFrameworkCore.SqlServer 2.0.0
- Microsoft.Extensions.Configuration.Json 2.0.0
我有一個切入點
class Program
{
private static IConfiguration Configuration { get; set; }
static void Main(string[] args)
{
IConfigurationRoot configurationRoot = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true)
.Build();
Configuration = configurationRoot;
// create service collection
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// create service provider
serviceCollection.BuildServiceProvider();
}
private static void ConfigureServices(ServiceCollection serviceCollection)
{
string connectionString = Configuration.GetConnectionString("DefaultConnection");
serviceCollection.AddDbContext<MyDbContext>(options => options.UseSqlServer(connectionString));
}
}
和appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "****"
}
}
2).NetStandard庫(包含的DbContext)
- Microsoft.EntityFrameworkCore 2.0.0
- Microsoft.EntityFrameworkCore.Tools 2.0.0
- 微軟.EntityFrameworkCore.SqlServer 2.0.0
我希望能夠使用dotnet ef migrations add [NAME]
創建一個遷移腳本,我已經制定出如果我在lib文件夾中運行命令,我可以將啓動項目作爲目標來運行遷移。
D:\Lib> dotnet ef migrations add InitialCreate -s ..\ConsoleApp\
我設法在同一文件夾中MyDbContext實現IDesignTimeDbContextFactory<MyDbContext>
我可以添加一個連接字符串,它運行完美添加一個類來得到這個工作。
public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
public MyDbContext CreateDbContext(string[] args)
{
DbContextOptionsBuilder<MyDbContext> builder = new DbContextOptionsBuilder<MyDbContext>();
builder.UseSqlServer("****", optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(MyDbContext).GetTypeInfo().Assembly.GetName().Name));
return new MyDbContext(builder.Options);
}
}
我的問題是,我想使用的連接字符串從 控制檯應用程序的appsettings.json內。
這是可能的嗎?我該怎麼做?
在此先感謝。