skip to Main Content

I have created an ASP.NET Core 6 MVC web app in Visual Studio Code, but I am having trouble connecting it with an already existing SQLite database file.

I tried adding the database file by moving it into the mvc files but it didn’t work

2

Answers


    1. Add Microsoft.EntityFrameworkCore.Sqlite package to your project with dotnet add package Microsoft.EntityFrameworkCore.Sqlite
    2. In the Startup.cs configure your DatabaseContext:
    services.AddDbContext<MyDbContext>(options =>
        options.UseSqlite(Configuration.GetConnectionString("MyConnection")));
    
    
    1. Define your Conenctionstring in your appsettings.json
    {
      "ConnectionStrings": {
        "MyConnection": "Data Source=mydatabase.db"
      }
    }
    
    

    *Note: Connectionstring can vary

    1. In your DatabaseContext add public DbSet<MyTable> MyTables { get; set; } *MyTable should be the name of your table
    2. In your Controller use dependency injection to get an instance if your database context
    private readonly MyDbContext _dbContext;
    
    public MyController(MyDbContext dbContext)
    {
        _dbContext = dbContext;
    }
    
    1. Query your database
    public IActionResult Index()
    {
        var myData = _dbContext.MyTables.ToList();
        return View(myData);
    }
    

    *Change query to your needs

    I hope this helps. If not, please do not hesitate to respond to me

    Login or Signup to reply.
  1. My working sample:
    DBfile
    enter image description here
    program.cs

    builder.Services.AddDbContext<UTsContext>(options =>
        options.UseSqlite("Filename=E:\IISPUB\UTs\test2.db3"));
    

    Context

        public class UTsContext : DbContext
        {
            public UTsContext (DbContextOptions<UTsContext> options)
                : base(options)
            {
            }
    
            public DbSet<Entry> Entry { get; set; } = default!;
        }
    

    Data Model

        public class Entry
        {
            public int ID {  get; set; }
            public DateTime RecordingTime { get; set; }
            public int Period { get; set; }
        }
    

    A simple controller with get method

        [ApiController]
        public class EntriesController : ControllerBase
        {
            private readonly UTsContext _context;
    
            public EntriesController(UTsContext context)
            {
                _context = context;
            }
    
            
            [HttpGet("test")]
            public async Task<ActionResult<IEnumerable<Entry>>> GetEntry()
            {
                return await _context.Entry.ToListAsync();
            }
         }
    

    test output
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search