EF Core 2.0 執行 Add-Migration 會出現錯誤:
PM> Add-Migration InitialCreation Unable to create an object of type 'OrderContext'. Add an implementation of 'IDesignTimeDbContextFactory<OrderContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
這是因為 EF Core 2.0 有改變 Tools 的作法,在 Asp.net
core 最佳的解法是:
WebHost.CreateDefaultBuilder(args)
如果是 Console program,可以用 emtpy constructor 的方式:
public class OrderContext : DbContext
{
public OrderContext() { }
public OrderContext(DbContextOptions<OrderContext> options) : base(options) { }
public DbSet<OrderProcess> OrderProcesses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=Msmtest;Trusted_Connection=True;");
}
}
重點在於 OnConfiguring 加上指定的 SqlServer connection。一旦產生 Migration 之後,就可以將
empty constructor comment 掉(因為可能會影響程式的正常邏輯)。
有問題嗎?歡迎一起討論喔!