[英]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.