1.-首先你不應該建立在控制器內部上下文,避免在依賴項中使用'new',因爲這會使你的代碼無法測試,在我使用UnitOfWork的情況下,我將它注入爲IUnitOfWork instan ce,這的確是MyConext的擴展,並且你會在StartUp類中注入它...爲此,我有一個私有方法(在單個私人調用中執行此操作):
private void AddEntityFrameworkAndDbContext(IServiceCollection services) { services.AddEntityFrameworkSqlServer();
var migrationsAssemblyName = typeof(MyContext).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<MyContext>(options =>
{
options.UseSqlServer(
"MY CONNECTION STRING GOES HERE (BUT I RETREIVE IT FROM ANOTHER SERVICE)",
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(migrationsAssemblyName);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
});
},
ServiceLifetime.Scoped // Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
).AddUnitOfWork<MyContext>(); // This is because I'm also using EF Core Unit of work NuGet Package
}
我打電話,從ConfigureServices(IServiceCollection服務),正如我所說,在啓動類
// Add EF, and UoW
AddEntityFrameworkAndDbContext(services);
2:二(私有方法,但我想說,這是你的真正的問題)我想說,你錯過了base.OnConfiguring(選項);在你的情況下,它應該是這樣的:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Server=(local);Database=VotingAppDB;User ID=sa;Password=123;");
}
base.OnConfiguring(optionsBuilder);
}
另外,請看一看這個答案我幾周前寫道: How to setup EF6 Migrations with ASP.NET Core
此外,的UnitOfWork項目值得一讀,取看看這裏:https://github.com/arch/UnitOfWork
我希望它能幫助,
胡安
我有確切的問題。我不知道如何解決它迄今。 – hidden
所以......你的數據庫有模式嗎?當我刪除我的模式,然後腳手架開始工作。 – hidden
我發現我的問題。我用VARCHAR(max)來定義列的長度。通常EF不理解,並且默默地失敗 – hidden