Search code examples
c#sqliteasp.net-core-mvc.net-6.0

How can I connect my SQLITE file to an ASP.NET Core 6 MVC app in Visual Studio Code?


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


Solution

  • 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