Search code examples
c#sql-serverentity-framework-coreasp.net-core-webapiin-memory-database

How to convert Web API project from EntityFramework.InMemory to using SQL Server?


I use Microsoft tutorial to create simple Web API solution, which use "In Memory" database:

Tutorial: Create a web API with ASP.NET Core

How to convert this solution to use an actual database? My database already exists, but I'm also open for solution by creating table(s) with database migration scripts.

For now I added a connection string to appsettings.json file, and believe that I need to

  1. remove package Microsoft.EntityFrameworkCore.InMemory
  2. add package Microsoft.EntityFrameworkCore.SqlServer
  3. connect context to my database, by using connection string

So how to do step #3 - I don't know.

Currently I have this code in Program.cs:

builder.Services.AddDbContext<TodoContext>(opt =>  opt.UseInMemoryDatabase("TodoList"));

I uploaded code to: https://github.com/sam-klok/WebApiCore7

NuGet packages I have:

enter image description here


Solution

  • After adding Microsoft.EntityFrameworkCore.SqlServer you can see a new extension method called UseSqlServer on dbcontext options like this:

    builder.Services.AddDbContext<TodoContext>(opt =>
      opt.UseSqlServer("YourDatabase_ConnectionString"));
    

    If you want to create migration for database first add this package

    Microsoft.EntityFrameworkCore.Tools

    and run this commands for creating migration files

    #for visual studio
    Add-Migration InitialCreate
    
    #for .Net Cli
    dotnet ef migrations add InitialCreate
    

    and for create or update database

    #for visual studio
    Update-Database
    
    #for .Net Cli
    dotnet ef database update