Home > OS >  Connection string in ASP.NET Core web API
Connection string in ASP.NET Core web API

Time:10-14

I have an SQLite database in my console project and this connection string works fine in the DbContext setup :

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
  optionsBuilder.UseSqlite("Data Source=PubDatabase.db")

When I compile the database is created in ConsoleApp>bin>debug>net6.0>PubDatabase.db. In my ASP.NET Core project I use appsettings.json to set the connection string :

"ConnectionStrings": {
"PubConnection": "Data Source=../PubDatabase.db"

I put the PubDatabase.db file inside this folder: APIProject>bin>debug>net6.0.

In Program.cs I use :

builder.Services.AddDbContext<PubContext>(
opt=>opt.UseSqlite(builder.Configuration.GetConnectionString("PubConnection"))

My DbContext :

namespace PublisherData;
public class PubContext:DbContext
{
 public DbSet<Author> Authors { get; set; }
 public DbSet<Book> Books { get; set; }
 public DbSet<Artist> Artists { get; set; }
 public DbSet<Cover> Covers { get; set; }

 public PubContext(DbContextOptions<PubContext> options)
 :base(options)
 {

 }

But When I try this in AuthorsController :

[Route("api/[controller]")]
[ApiController]
public class AuthorsController : ControllerBase
{
    private readonly PubContext _context;

    public AuthorsController(PubContext context)
    {
        _context = context;
    }

    // GET: api/Authors
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Author>>> GetAuthors()
    {
        return await _context.Authors.ToListAsync();
    }

I get this error :

enter image description here

Where should I put the database to reach it with the connection string?

CodePudding user response:

I did a simple test, you can follow my steps below.

First, install NuGet package:

Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools

Then, create the context:

public class SqlContext : DbContext 
    {
        public SqlContext(DbContextOptions<SqlContext> Options) : base(Options)
        {
        }
        
        public DbSet<Author> Authors { get; set; } 

    }

Add a connection string:

appsettings.json:

"ConnectionStrings": { 
    "WebApiDatabase": "Data Source=PubDatabase.db"
  }

Program.cs:

builder.Services.AddEntityFrameworkSqlite().AddDbContext<SqlContext>(opt => opt.UseSqlite(builder.Configuration.GetConnectionString("WebApiDatabase")));

Finally, migrate and update the database:

Add-Migration InitialCreate
Update-Database

The three files appear in the directory structure:

enter image description here

Test Result:

enter image description here

Hope this can help you.

  • Related