SQLite CodeFirst示例

时间:2018-08-02 08:20:40

标签: c# sqlite entity-framework-6 ef-code-first

我尝试使用SQLite为实体框架运行CodeFirst示例。 NuGet软件包SQLite.CodeFirst已安装并且运行无错误 但它不会创建SQLite数据库。 这是我的代码:

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();
            }
        }
    }
}

连接字符串为:

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

1 个答案:

答案 0 :(得分:0)

DbContext类具有一个名为.Migrate()的方法,它将通过迁移管道并创建数据库(如果尚不存在的话)。

以下是来源:Entity Framework Migrations