Search code examples
c#sqliteentity-framework-coreef-core-5.0

"No such table" error after initial migration in Entity Framework Core


(Win7 x64, Visual Studio 2019, Entity Framework Core/SQLite/Tools v.5.0.2)

I follow this

https://learn.microsoft.com/ru-ru/ef/core/get-started/overview/first-app?tabs=visual-studio

tutorial on Entity Framework Core. I copy/pasted all the code just to be sure and applied initial migration with Nuget console. The console reported that the migration was applied successfully according to the log:

PM> Update-Database
Build started...
Build succeeded.
Applying migration '20210121202929_InitialCreate'.
Done.
PM> Update-Database
Build started...
Build succeeded.
No migrations were applied. The database is already up to date.
Done.
PM>  

Though the file icons of the database files created indicate that there might be a problem:

enter image description here

I tried to run the main code from tutorial, but got an error

No such table: Blogs

Code:

namespace EFCTest6
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                // Create
                Console.WriteLine("Inserting a new blog");
                // ERROR! SqliteException: SQLite Error 1: 'no such table: Blogs'.
                db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                db.SaveChanges();

                // Read
                Console.WriteLine("Querying for a blog");
                var blog = db.Blogs
                    .OrderBy(b => b.BlogId)
                    .First();

                // Update
                Console.WriteLine("Updating the blog and adding a post");
                blog.Url = "https://devblogs.microsoft.com/dotnet";
                blog.Posts.Add(
                    new Post
                    {
                        Title = "Hello World",
                        Content = "I wrote an app using EF Core!"
                    });
                db.SaveChanges();

                // Delete
                Console.WriteLine("Delete the blog");
                db.Remove(blog);
                db.SaveChanges();
            }
        }
    }
}

I also tried to change the exception-generating line from db.Add(...) to db.Blogs.Add(...) but it generates the same exception.


Solution

  • Make sure that the table exists in the database. Many people, myself included sometimes, would add the table to the Context in visual studio and then Apply the migration, but actually forget to update the database.

    Type the following in the Package-Manager Console (Tools > Nuget Package Manager > Package manager Console) and type this :

    Add-Migration "Blogs"

    This will add the migration if it doesn't exist already. Then Type

    Update-Database