Display Name
Display Name

Reputation: 15071

What causes this "no such table exception"?

I created a .net core console application project as follows. I think several months ago this can be run without error but now it does not work anymore with the following error.

enter image description here

Code

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
  </ItemGroup>

</Project>


using Microsoft.EntityFrameworkCore;
using System;

namespace ConsoleApp4
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class SchoolContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=MyDatabase.db");
        }
        public DbSet<Student> Students { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (SchoolContext _schoolContext = new SchoolContext())
            {
                Student student = new Student() { Name = "Billy" };


                _schoolContext.Students.Add(student);


                int result = _schoolContext.SaveChanges();

                Console.WriteLine($"There is(are) {result} student(s) added.");
            }
        }
    }
}

Question

What causes this error and how to solve it?

Edit

For your reference, the database and table do exist as follows.

enter image description here

I am working on Visual Studio 2017 15.8.0 Preview 1.1.

Upvotes: 4

Views: 1721

Answers (2)

Display Name
Display Name

Reputation: 15071

After wasting several hours, I found the solution. Unlike MyDatabase.db generated by migration in the project root, MyDatabase.db generated by default in $OutDir does not have Students table.

To solve it, I have to apply the following configuration on the root MyDatabase.db.

enter image description here

Probably this issue is caused by VS 2017 Preview.

Upvotes: 8

tmaj
tmaj

Reputation: 34947

The error means that the table does not exist in the database you're connected to.

Upvotes: 0

Related Questions