.net Entity Framework 6 with SQLite 3 Code First - 不会创建表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22174212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:41:16  来源:igfitidea点击:

Entity Framework 6 with SQLite 3 Code First - Won't create tables

.netsqliteef-code-firstentity-framework-6system.data.sqlite

提问by user1192887

Using latest versions of EF6 and SQLite from NuGet. I finally got the app.config file to work after some useful posts on Stackoverflow. Now the problem is that the tables are not being created although the database is.

使用来自 NuGet 的最新版本的 EF6 和 SQLite。在 Stackoverflow 上发表了一些有用的帖子后,我终于让 app.config 文件工作了。现在的问题是,尽管数据库已创建,但并未创建表。

My app.config:

我的 app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SQLite"
                type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite" />
      <add name="SQLite Data Provider"
           invariant="System.Data.SQLite"
           description=".Net Framework Data Provider for SQLite"
           type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider (Entity Framework 6)"
           invariant="System.Data.SQLite.EF6"
           description=".Net Framework Data Provider for SQLite (Entity Framework 6)"
           type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
    </DbProviderFactories>
  </system.data>
  <connectionStrings>
    <add name="MyDBContext"
          connectionString="Data Source=|DataDirectory|MyDB.sqlite"
          providerName="System.Data.SQLite" />
  </connectionStrings>
</configuration>

My simple test program:

我的简单测试程序:

class Program
{
    static void Main(string[] args)
    {
        using (var db = new MyDBContext())
        {
            db.Notes.Add(new Note { Text = "Hello, world" });
            db.Notes.Add(new Note { Text = "A second note" });
            db.Notes.Add(new Note { Text = "F Sharp" });
            db.SaveChanges();
        }

        using (var db = new MyDBContext())
        {
            foreach (var note in db.Notes)
            {
                Console.WriteLine("Note {0} = {1}", note.NoteId, note.Text);
            }
        }

        Console.Write("Press any key . . . ");
        Console.ReadKey();
    }

    public class Note
    {
        public long NoteId { get; set; }
        public string Text { get; set; }
    }

    public class MyDBContext : DbContext
    {
        // default constructor should do this automatically but fails in this case
        public MyDBContext()
            : base("MyDBContext")
        {

        }
        public DbSet<Note> Notes { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

If I create the table manually the program works fine and the table is updated. If I delete the database, EF creates it but doesn't create the table and the program fails when it attempts to read back the data with an error message that the table does not exist.

如果我手动创建表,程序可以正常工作并且表会更新。如果我删除数据库,EF 会创建它但不会创建表,并且程序在尝试读回数据时会失败,并显示表不存在的错误消息。

Has anyone managed to get Code First working with EF6 yet? Would appreciate help/guidance on this as I'm now completely stuck!!!

有没有人设法让 Code First 与 EF6 一起工作?非常感谢这方面的帮助/指导,因为我现在完全卡住了!!!

Thanks all.

谢谢大家。

采纳答案by kjbartel

Unfortunately, the EF6 provider implementation in System.Data.SQLite.EF6doesn't support creating tables. I downloaded the SQLite source code to have a look but couldn't find anything for creating tables and for migrations. The EF6 provider is basically the same as their Linq implementation so it's all aimed at querying the database rather than modifying it.

不幸的是,EF6 提供程序实现System.Data.SQLite.EF6不支持创建表。我下载了 SQLite 源代码来查看,但找不到用于创建表和迁移的任何内容。EF6 提供程序与它们的 Linq 实现基本相同,因此它们都旨在查询数据库而不是修改它。

I currently do all of my work with SQL Server and generate sql scripts for SQLite using the SQL Server Compact & SQLite Toolbox. The scripts can then be run using an SQLiteCommandto simulate migrations.

我目前使用 SQL Server 完成所有工作,并使用SQL Server Compact & SQLite Toolbox为 SQLite 生成 sql 脚本。然后可以使用SQLiteCommand模拟迁移来运行脚本。

Update

更新

In EF7support for SQL server compact has been dropped and a new provider for SQLite is being developed by the EF team. The provider will use Microsoft's managed SQLite wrapper project, Microsoft.Data.SQLiterather than the System.Data.SQLiteproject. This will also allow for using EF7 on iOS, Android, Windows Phone / Mobile, Linux, Mac etc. as Microsoft's wrapper is being developed as a portable library.

EF7 中,已经取消了对 SQL server compact 的支持,EF 团队正在开发一个新的 SQLite 提供程序。提供程序将使用 Microsoft 的托管 SQLite 包装器项目,Microsoft.Data.SQLite而不是该System.Data.SQLite项目。这也将允许在 iOS、Android、Windows Phone/Mobile、Linux、Mac 等上使用 EF7,因为 Microsoft 的包装器正在开发为一个便携式库。

It's all still in beta but you can get nuget packages from the ASP.Net development feeds at MyGet (dev, master, release) if you wish to have a look. Look for the EntityFramework.SQLitepackage.

它仍处于测试阶段,但如果您想看一看,您可以从 MyGet(devmasterrelease)的 ASP.Net 开发提要中获取 nuget 包。寻找EntityFramework.SQLite包裹。

回答by msallin

I started with the code from fried and created a project which lets you use CodeFirst. The project is available open source on GitHubor as NuGet Package.

我从 Fried 的代码开始,并创建了一个项目,让您可以使用 CodeFirst。该项目可在GitHub开源或作为NuGet 包

If you encounter any problems or miss a feature, feel free to open a new issue on GitHub. Of course PRs are very welcome.

如果您遇到任何问题或遗漏了某个功能,请随时在 GitHub 上打开一个新问题。当然,PR 是非常受欢迎的。

Edit (26.04.2016):

编辑(26.04.2016):

In the meantime I did a lot in this project.

与此同时,我在这个项目中做了很多。

The following (default EF) functionality is supported:

支持以下(默认 EF)功能:

  • Tables from classes (supported annotations: Table)
  • Columns from properties (supported annotations: Column, Key, MaxLength, Required, NotMapped, DatabaseGenerated, Index)
  • PrimaryKey constraint (Key annotation, key composites are supported)
  • ForeignKey constraint (1-n relationships, support for 'Cascade on delete')
  • Not Null constraint
  • Auto increment (an int PrimaryKey will automatically be incremented)
  • Index (Decorate columns with the Index attribute. Indices are automatically created for foreign keys by default. To prevent this you can remove the convetion ForeignKeyIndexConvention)
  • 来自类的表格(支持的注释:表格)
  • 来自属性的列(支持的注释:Column、Key、MaxLength、Required、NotMapped、DatabaseGenerated、Index)
  • PrimaryKey 约束(键注解,支持键组合)
  • 外键约束(1-n 关系,支持“级联删除”)
  • 非空约束
  • 自动递增(int PrimaryKey 将自动递增)
  • 索引(使用 Index 属性装饰列。默认情况下会自动为外键创建索引。为了防止这种情况,您可以删除对流 ForeignKeyIndexConvention)

There are also some features exclusive for SQLite, which are not supported by default:

还有一些 SQLite 独有的特性,默认情况下是不支持的:

  • Unique constraint (Decorate columns with the UniqueAttribute, which is part of this library)
  • Collate constraint (Decorate columns with the CollateAttribute, which is part of this library)
  • 唯一约束(使用 UniqueAttribute 装饰列,这是该库的一部分)
  • 整理约束(使用 Collat​​eAttribute 装饰列,这是该库的一部分)

There are two ways to use the functionality of this library.

有两种方法可以使用这个库的功能。

  1. Make use of the DbInitializers:

    • SqliteCreateDatabaseIfNotExists
    • SqliteDropCreateDatabaseAlways
    • SqliteDropCreateDatabaseWhenModelChanges
  2. Get more control by using one of the following two classes:

    • SqliteSqlGenerator (creates the SQL based on a EdmModel)
    • SqliteDatabaseCreator (creates a new SQLite database based on a Database and DbModel)
  1. 使用 DbInitializers:

    • SqliteCreateDatabaseIfNotExists
    • SqliteDropCreateDatabaseAlways
    • SqliteDropCreateDatabaseWhenModelChanges
  2. 通过使用以下两个类之一获得更多控制:

    • SqliteSqlGenerator(基于 EdmModel 创建 SQL)
    • SqliteDatabaseCreator(基于一个Database 和DbModel 创建一个新的SQLite 数据库)

Edit (30.05.2020):As EF 6 now supports .NET Core 3 and above, I adjusted the library to support .NET Standard 2.1 as well. The following .NET framework versions are supported:

编辑 (30.05.2020):由于 EF 6 现在支持 .NET Core 3 及更高版本,我调整了库以支持 .NET Standard 2.1。支持以下 .NET 框架版本:

  • .NET 4.0 (uses net40)
  • .NET 4.5-4.8 (uses net45)
  • .NET Core 3.0-3.1 (uses netstandard2.1)
  • .NET 4.0(使用 net40)
  • .NET 4.5-4.8(使用 net45)
  • .NET Core 3.0-3.1(使用 netstandard2.1)

回答by fried

I decided to write my own rudimentary database initializer to solve this problem.

我决定编写自己的基本数据库初始化程序来解决这个问题。

You can check it out here: https://gist.github.com/flaub/1968486e1b3f2b9fddaf

你可以在这里查看:https: //gist.github.com/flaub/1968486e1b3f2b9fddaf

It supports:

它支持:

  • Many-to-Many relationships
  • Code-First data annotations like:
    • [Key]
    • [Required]
    • [Index]
    • [ForeignKey]
  • 多对多关系
  • Code-First 数据注释,例如:
    • [钥匙]
    • [必需的]
    • [指数]
    • [外键]