[英]How to generate a SQL Server compatible database with Entity Framework (code first)
我正在按照本教程https://www.freecodecamp.org/news/an-awesome-guide-on-how-to-build-restful-apis-with-asp-net-core-87b818123e28/的操作 ,但我一切正常可以正常工作,但此示例API使用的是InMemoryDatabase
選項。 我想使用一個SQL Server數據庫(我正在使用代碼優先方法)。
我試圖在SQL Server Management Studio中創建一個沒有表的數據庫,並在Startup
類中使用帶有以下代碼的連接字符串,它正在工作並將數據保存到數據庫中,但是它沒有出現在SQL Server Management Studio中。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<GameCollectionDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DBGAMESCOLLECTION"));
// options.UseInMemoryDatabase("GAME_COLLECTION_DB");
});
services.AddScoped<IUsersRepository, UsersRepository>();
services.AddScoped<ICollectionsRepository, CollectionsRepository>();
services.AddScoped<IGamesRepository, GamesRepository>();
services.AddScoped<IUsersService, UsersService>();
services.AddScoped<ICollectionsService, CollectionsService>();
services.AddScoped<IGamesService, GamesService>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddAutoMapper();
}
我的appsettings.json
看起來像這樣
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DBGAMESCOLLECTION": "Server=(localdb)\\mssqllocaldb;Database=GAMES_COLLECTION_DB;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"AllowedHosts": "*"
}
我想要做的就是讓Entity Framework根據聲明的模型在本地計算機中創建數據庫,並在SQL Server中提供結果數據庫以用於進行查詢和存儲過程。
(更新)
我想我應該更清楚。 我使用代碼優先方法創建了REST API,因為我希望創建模型並基於該模型獲取數據庫文件或腳本。 這是我第一次獨自實現EF,因此起初我將InMemoryDatabase選項用於上下文,但我知道那僅用於測試目的。 API按預期工作后,我繼續使用真實的數據庫進行持久化。 所以我將此添加到了Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<GameCollectionDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DBGAMESCOLLECTION"));
//options.UseInMemoryDatabase("GAME_COLLECTION_DB");
});
}
我的appsettings.json就這樣結束了。
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DBGAMESCOLLECTION": "Server=(localdb)\\mssqllocaldb;Database=GAMES_COLLECTION_DB;Trusted_Connection=True;"
},
"AllowedHosts": "*"
}
到那時為止,數據庫已停止工作,並且在停止上下文后仍在保存數據,但是我想知道數據庫的創建位置是因為在SSMS中它沒有顯示在我的計算機中。 最終,我發現由於連接字符串,我正在使用sqlexpress的另一個實例,當我在SSMS服務器名稱中連接到'(LocalDb)\\ MSSQLLocalDB'引擎時,它在那里。
現在,我有了一個sql server數據庫和一個連接字符串,以便可以同時進行工作。 那么我的問題是,這種配置將如何在現實生活中發揮作用? 我在appsettings.json中編寫的連接字符串是要創建數據庫的地方? 所以如果我把服務器IP放在那兒呢?
嘗試以下...
在您的appsettings.json
(“字符串”不是“字符串”):
"ConnectionString": {
"DBGAMESCOLLECTION": "..."
}
在Startup.cs
:
services.AddDbContext<ApplicationContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:DBGAMESCOLLECTION"]));
並且您必須添加Code-First Migrations 。 遷移會根據您的模型自動創建數據庫。 就像是:
PM> Add-Migration *Some_Description*
PM> update-database
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.