【问题标题】:SQLite CodeFirst exampleSQLite CodeFirst 示例
【发布时间】:2019-01-09 22:38:32
【问题描述】:

我尝试使用 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>

【问题讨论】:

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


    【解决方案1】:

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

    这是一个来源:Entity Framework Migrations

    【讨论】:

    • 对不起,这个框架中不存在 Datebase.Migrate() :-(
    • 那么您可以尝试的另一个选项是使用迁移工具自己创建数据库。打开您的Package Manager Console 并键入以下内容:&gt; enable-migrations &gt; add-migration "Name you want" 这将在您的项目中创建一个迁移文件夹,其中包含构建数据库架构所需的脚手架,您不必触摸该文件夹中的文件。最后运行 &gt; update-database 使用之前创建的迁移创建数据库。
    • 我做了,我在哪里可以找到数据库?
    • 如果它没有出现在您的项目文件中,请检查您的项目的 bin 文件夹。或者只是使用资源管理器在项目文件夹中搜索文件。
    【解决方案2】:

    我在您的代码中指出的是,您的代码中缺少 MyContext 类的 constructor。添加带有基础的构造器,然后重试。

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

    在您的类中添加构造函数后,如果您的项目中还没有Migrations 文件夹,您必须编写如下命令:

    1. 在您的视觉工作室中,转到 view -&gt; other windows -&gt; package manager console
    2. 要启用迁移,请运行 enable-migrations 。执行后,您将找到 Migrations 文件夹。
    3. 现在为当前​​项目添加带有消息的迁移,运行add-migration InitialCreate
    4. 要更新数据库,运行update-database

    刷新/重新连接您的服务器/数据库。你会在那里找到数据库。

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 2010-11-28
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 2016-01-30
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多