'SQLite CodeFirst example

I try to run a CodeFirst example for Entity Framwork with SQLite. The NuGet Package SQLite.CodeFirst is installed and runs without errors but it doesn´t create a SQLite DB. This is my code:

using SQLite.CodeFirst;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Text;

namespace EF6SqliteExample
{
    class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class MyContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var model = modelBuilder.Build(Database.Connection);
            ISqlGenerator sqlGenerator = new SqliteSqlGenerator();
            string sql = sqlGenerator.Generate(model.StoreModel);
        }
        public DbSet<Person> Persons { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new MyContext())
            {
                var person = new Person() { Name = "John" };
                db.Persons.Add(person);
                db.SaveChanges();
            }
        }
    }
}

The Connection-String is:

<connectionStrings>
    <add name="MyDB" connectionString="data source=.\MyDB.sqlite" providerName="System.Data.SQLite" />
  </connectionStrings>


Solution 1:[1]

The DbContext class has a method called .Migrate() which will go through the migrations pipeline and create your database if it does not already exist.

Here's a source: Entity Framework Migrations

Solution 2:[2]

What I pointed out in your code is, constructor of class MyContext is missing in your code. Add contructor with base and try again.

public MyContext() : base("MyDB")
{
   
}

after adding constructor in your class, if the Migrations folder is not available yet in your project, you have to write some command as below:

  1. In your visual studio, go to view -> other windows -> package manager console
  2. To enable migration, run enable-migrations . After executing it, you will find Migrations folder.
  3. now add migration with message for current project, run add-migration InitialCreate
  4. to update Database, run update-database

Refresh/Reconnect you server/db. You will find the db there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cristian Moraru
Solution 2 Pranta Palit