简体   繁体   English

如何使用实体框架生成与SQL Server兼容的数据库(代码优先)

[英]How to generate a SQL Server compatible database with Entity Framework (code first)

I was following this tutorial https://www.freecodecamp.org/news/an-awesome-guide-on-how-to-build-restful-apis-with-asp-net-core-87b818123e28/ and I got everything right and working but this example API is using the InMemoryDatabase option. 我正在按照本教程https://www.freecodecamp.org/news/an-awesome-guide-on-how-to-build-restful-apis-with-asp-net-core-87b818123e28/的操作 ,但我一切正常可以正常工作,但此示例API使用的是InMemoryDatabase选项。 I want to use a SQL Server database with it (I'm using the code first approach). 我想使用一个SQL Server数据库(我正在使用代码优先方法)。

I have tried to create a database with no tables in SQL Server Management Studio and use a connection string with the following code in my Startup class, and it is working and saving data to the database but it does not appear in SQL Server Management Studio. 我试图在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();
}

My appsettings.json looks like this 我的appsettings.json看起来像这样

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
     "DBGAMESCOLLECTION": "Server=(localdb)\\mssqllocaldb;Database=GAMES_COLLECTION_DB;Trusted_Connection=True;MultipleActiveResultSets=true"
   },
   "AllowedHosts": "*"
 }

All I want is to make Entity Framework create the database in my local machine based on the models I declared and the resulting database to be available in SQL Server for making queries and stored procedures. 我想要做的就是让Entity Framework根据声明的模型在本地计算机中创建数据库,并在SQL Server中提供结果数据库以用于进行查询和存储过程。

(UPDATE) (更新)

I guess I should be clearer. 我想我应该更清楚。 I created my REST API with a code first approach because I expected to create models and based on that get a database file or script. 我使用代码优先方法创建了REST API,因为我希望创建模型并基于该模型获取数据库文件或脚本。 It is the first time I implemented EF all by myself so at first I used the InMemoryDatabase option for my context but I knew that was only for testing purposes. 这是我第一次独自实现EF,因此起初我将InMemoryDatabase选项用于上下文,但我知道那仅用于测试目的。 After the API worked as expected I moved on to use a real database for persistance. API按预期工作后,我继续使用真实的数据库进行持久化。 So I added this to my Startup.cs 所以我将此添加到了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");

        });
}

And my appsettings.json ended like this. 我的appsettings.json就这样结束了。

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DBGAMESCOLLECTION": "Server=(localdb)\\mssqllocaldb;Database=GAMES_COLLECTION_DB;Trusted_Connection=True;"
  },
  "AllowedHosts": "*"
}

Up to that point the database worked and data was being saved after stopping the context but I was wondering where my database was created because in SSMS it didn't show up in my machine. 到那时为止,数据库已停止工作,并且在停止上下文后仍在保存数据,但是我想知道数据库的创建位置是因为在SSMS中它没有显示在我的计算机中。 I finally found that because of the connections string I was using another instance of sqlexpress and when I connected to the '(LocalDb)\\MSSQLLocalDB' engine in SSMS server name it was there. 最终,我发现由于连接字符串,我正在使用sqlexpress的另一个实例,当我在SSMS服务器名称中连接到'(LocalDb)\\ MSSQLLocalDB'引擎时,它在那里。

So I now got an sql server database and a connection string to it so I can work in the mean while. 现在,我有了一个sql server数据库和一个连接字符串,以便可以同时进行工作。 My question then is, How is this configuration gonna work in real life? 那么我的问题是,这种配置将如何在现实生活中发挥作用? the connection string I wrote in appsettings.json is the place where the database is going to be created? 我在appsettings.json中编写的连接字符串是要创建数据库的地方? so if I put a server ip it will be there? 所以如果我把服务器IP放在那儿呢?

Try the following... 尝试以下...
In your appsettings.json ('String' not 'Strings'): 在您的appsettings.json (“字符串”不是“字符串”):

"ConnectionString": {
    "DBGAMESCOLLECTION": "..."
  }

In Startup.cs : Startup.cs

services.AddDbContext<ApplicationContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:DBGAMESCOLLECTION"]));

And you have to add Code-First Migrations . 并且您必须添加Code-First Migrations Migrations automate the creation of database based on your Models. 迁移会根据您的模型自动创建数据库。 Something like: 就像是:

PM> Add-Migration *Some_Description*

PM> update-database

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架代码首先确定数据库是否兼容 - Entity Framework code first determine if a Database is compatible 实体框架代码首先在SQL Server Management Studio中没有数据库 - Entity Framework Code First no database in SQL Server Management Studio 实体框架数据库优先-SQL Server - Entity Framework database-first with SQL Server 外部SQL服务器上的实体框架代码优先 - Entity Framework Code First on external SQL server 实体框架代码优先:使用&#39;Update-Database&#39;生成SQL脚本在解析时会产生XML错误 - Entity Framework Code-First: Generate SQL script with 'Update-Database' produces XML error while parsing 实体框架:如何生成一个SQL Server model - Entity framework : how to generate a SQL Server model 如果我们使用具有代码优先方法的Entity框架,是否可以在给定路径上创建数据库(Sql Server compact)? - Is possible to create a database (Sql Server compact) on a given path if we use Entity framework with code-first approach? 将数据库从嵌入式更改为SQL Server Express后,Entity Framework 4.1代码第一个模型兼容性问题 - Entity Framework 4.1 code first model compatibility issue after changing database from embedded to SQL Server Express MVC4代码优先实体框架将大文件上传到SQL Server数据库 - MVC4 Code First Entity Framework Upload large files to a SQL Server database Entity Framework Code First 在服务器资源管理器中找不到数据库 - Entity Framework Code First can't find database in server explorer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM