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.
db.Tasks.Add(...)
instead ofdb.Add(...)
!Data Source = TestDatabase.db
successfully?TestDatabase.db
file in the connection string. I mean something like that...UseSqlite(@"Data Source= C:\TestDatabase.db ")
. replaceC:\TestDatabase.db
with your own address.