wpf 实体框架 6 不在 SQLite 数据库中创建表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35304899/
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-13 13:39:59  来源:igfitidea点击:

Entity Framework 6 not creating tables in SQLite database

c#wpfsqliteef-code-firstentity-framework-6

提问by Kyle Humfeld

I'm trying to get System.Data.SQLite to work with Entity Framework 6, using the Code First approach in my C#.NET (4.5.2) WPF project.

我正在尝试使用我的 C#.NET (4.5.2) WPF 项目中的 Code First 方法让 System.Data.SQLite 与 Entity Framework 6 一起工作。

I've looked over and tried to follow the instructions in the following places (among others), but they appear to be either out of date, for a different dbms, not for Code First, or some combination of the above.

我已经查看并尝试按照以下位置(以及其他位置)中的说明进行操作,但它们似乎已过时,对于不同的 dbms,而不是 Code First,或上述的某种组合。

https://msdn.microsoft.com/en-us/data/jj592674

https://msdn.microsoft.com/en-us/data/jj592674

https://msdn.microsoft.com/en-us/data/jj592674.aspx

https://msdn.microsoft.com/en-us/data/jj592674.aspx

http://nullskull.com/a/10476742/sqlite-in-wpf-with-entity-framework-6.aspx

http://nullskull.com/a/10476742/sqlite-in-wpf-with-entity-framework-6.aspx

Entity Framework 6 + SQLite

实体框架 6 + SQLite

I think I've finally got my App.config file set up correctly, as follows:

我想我终于正确设置了我的 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.2" />
  </startup>
  <entityFramework>
    <!-- from: https://stackoverflow.com/questions/14510096/entity-framework-6-sqlite -->
    <providers>
        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" /> 
        <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
     </defaultConnectionFactory>
  </entityFramework>
  <connectionStrings>
    <add name="MyDatabase" connectionString="Data Source=.\DataFile\myDatabase.sqlite" providerName="System.Data.SQLite" />
  </connectionStrings>
    <system.data>
    <!-- from: https://stackoverflow.com/questions/14510096/entity-framework-6-sqlite -->
    <DbProviderFactories>
        <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" /> 
        <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" />
    </DbProviderFactories>
    </system.data>
</configuration>

My DbContext definition is as follows:

我的 DbContext 定义如下:

public class MyDataContext : DbContext
{
    public MyDataContext() :  base("name=MyDatabase")
    {
    }
    public DbSet<DataItem> DataItems { get; set; }
}

My DataItem class is as follows:

我的 DataItem 类如下:

public class DataItem
{
    [Key]
    public int MyInt { get; set; }
    public string MyString { get; set; }
}

And I'm trying to call the context like this:

我正在尝试像这样调用上下文:

using (var db = new MyDataContext())
{
    DataItem item = new DataItem { MyInt = 19, MyString = "nineteen" };
    db.DataItems.Add(item);
    try
    {
        db.SaveChanges();
    }
    catch (Exception ex)
    {
        var x = ex.InnerException;
        Debug.WriteLine("Inner Exception: {0}", x);
        throw;
    }

}

As I expect, when I instantiate MyDataContext, the myDatabase.sqlitefile gets created in my bin\debug\DataFiledirectory. However, when I try to call db.SaveChanges(), an exception is caught.

正如我所料,当我实例化时MyDataContextmyDatabase.sqlite文件会在我的bin\debug\DataFile目录中创建。但是,当我尝试调用时db.SaveChanges(),会捕获到异常。

The InnerException of this exception is System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SQLite.SQLiteException: SQL logic error or missing database no such table: DataItems

此异常的 InnerException 是 System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SQLite.SQLiteException: SQL logic error or missing database no such table: DataItems

When I look in the DataFile directory, the myDatabase.sqlite file is zero bytes. This tells me that though the DbContext found the proper filename for the new database file from the app.config file, it did not do its Code First creation of tables within the database as it is supposed to.

当我查看 DataFile 目录时,myDatabase.sqlite 文件为零字节。这告诉我,尽管 DbContext 从 app.config 文件中找到了新数据库文件的正确文件名,但它并没有像它应该的那样在数据库中执行代码优先创建表。

Is there something obvious I'm missing here? The examples all assume this (extremely critical) step works and everything in EF6 follows from a working properly set up database.

有什么明显的我在这里失踪了吗?这些示例都假设此(极其关键的)步骤有效,并且 EF6 中的所有内容都遵循正常工作的数据库设置。

Thanks in advance for any help you can offer me on this.

在此先感谢您提供的任何帮助。

采纳答案by Kyle Humfeld

According to Entity Framework 6 with SQLite 3 Code First - Won't create tables, EF6 doesn't create tables when used with SQLite, so I had to do so myself.

根据Entity Framework 6 with SQLite 3 Code First - Won't create tables,EF6 在与 SQLite 一起使用时不会创建表,所以我必须自己这样做。

I was able to create a SQLite database using DB Browser for SQLite, and create the tables in it myself. I had to be careful to make sure the structure of the tables I created matched the properties in my Model classes, and to use the [Key] annotation on the Model classes to indicate which field is the primary key field.

我能够使用DB Browser for SQLite创建一个 SQLite 数据库,并自己在其中创建表。我必须小心确保我创建的表的结构与我的模型类中的属性匹配,并使用模型类上的 [Key] 注释来指示哪个字段是主键字段。

Importantly, I had to Add Existing Item in Visual Studio to grab that file and make sure that Visual Studio knew about the file.

重要的是,我必须在 Visual Studio 中添加现有项目来获取该文件并确保 Visual Studio 知道该文件。

Also, importantly, I had to go to the Properties of that file and set its 'Copy to Output Directory' property to 'Copy if Newer', so that the database makes its way to the bin/debug or bin/release directory when I run the app. If I didn't do this, the database would not exist at runtime, which would cause a runtime crash.

此外,重要的是,我必须转到该文件的属性并将其“复制到输出目录”属性设置为“如果较新则复制”,以便数据库在我进入 bin/debug 或 bin/release 目录时运行应用程序。如果我不这样做,数据库在运行时将不存在,这将导致运行时崩溃。