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
Microsoft.EntityFrameworkCore.InMemory
Microsoft.EntityFrameworkCore.SqlServer
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:
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