"No such table" on code-first EntityFrameworkCore.Sqlite 3.1.1 when table exists

c# entity-framework-core sqlite

Question

I am following this article on how to work with Entity Framework Core and Sqlite. My objects are named differently and have different properties but that's about the only change I have made to the code given in the article.

I used migrations to create a database and a table in it. I opened the database using SQLiteStudio and can see the table "Tasks" is created there with the proper columns.

However I get the error "No such table: Tasks" when trying to save a new "Task" object in it.

Here is my code:

Model.cs

public class TaskContext : DbContext
{
    public DbSet<Task> Tasks { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite("Data Source = TestDatabase.db");
}

Task.cs

public class Task
{
    public int TaskId { get; set; }
    public string TaskName { get; set; }
    public DateTime LastExecutionDateTime { get; set; }
    public TimeSpan ExecutionInterval { get; set; }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Start.");

        using (var db = new TaskContext())
        {
            Console.WriteLine("Saving new task...");
            db.Add(new Task { TaskId=1, TaskName = "test", ExecutionInterval = new TimeSpan(0, 0, 10), LastExecutionDateTime = DateTime.Now });
            db.SaveChanges();
        }

        Console.WriteLine("End.");
    }
}

Just like the article said, I have included the Nuget Packages Microsoft.EntityFrameworkCore.Design and Microsoft.EntityFrameworkCore.Sqlite, enabled migrations and did an initial migration (that's how the database got created). I have a folder "Migrations" and a table "__EFMigrationsHistory" in the database.

So I can't figure out why it would throw such an error instead of add a new record in the table.

1
0
1/19/2020 7:27:00 PM

Popular Answer

Well, this certainly was retarded.

For some reason, migrations creates the database at the foot of your project. When debugging everything is deployed in a series of directories that start with "bin" and end in "netcoreappX.X".

Guess where a hardcoded relative path leads to?
Also you better guess there's ALSO a *.db file in that "netcoreapp" that is 0KB large.

Changing the path from relative to absolute fixes things.

0
1/20/2020 7:24:10 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow