SQLite与实体框架6"没有这样的表"

Gre*_*che 2 c# sqlite entity-framework

我试图首先用SQLiteEntityFramework 6代码实现这个问题.我可以创建数据库并且有一个文件(虽然是空的),但是当我尝试向数据库添加一个条目时,它说没有这样的表.然而,当我尝试手动创建表时()它告诉我表已经存在.db.Database.ExecuteSqlCommand("CREATE TABLE etc.)

我已经发现了一些关于这个的问题,但是它们都是关于不是绝对的道路,这根本不是这里的情况.

上下文

//Context:
class MediaContext : DbContext
{
    public DbSet<MediaModel> Media { get; set; }

    public MediaContext(string filename): base(new SQLiteConnection() {
        ConnectionString =
            new SQLiteConnectionStringBuilder()
            { DataSource = filename, ForeignKeys = false }
            .ConnectionString
    }, true)
    {

    }        
}
Run Code Online (Sandbox Code Playgroud)

DAL

//In the DAL:
public DataAccessLayer(string path)
{
   _path = Path.GetFullPath(path); //<--The path already comes full in, I'm just paranoid at this point.
   _connectionPath = _path + @"\MyDatabase.sqlite";

   using (var db = new MediaContext(_connectionPath))
   {
      db.Database.CreateIfNotExists();
      db.Database.Initialize(false);                

       db.SaveChanges();
   }

   public void Generate()
   {
       using (var db = new MediaContext(_connectionPath))
       {
          db.Media.Add(new MediaModel("test"));
          db.SaveChanges(); //<--SQLiteException: SQL logic error or missing database: no such table: MediaModels

        }
    }
Run Code Online (Sandbox Code Playgroud)

App.Config中

//App.config:
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v13.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.data>
    <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.EF6" />
      <add name="SQLite Data Provider" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
    </DbProviderFactories>
  </system.data>
</configuration>
Run Code Online (Sandbox Code Playgroud)

Özg*_*gür 7

这是微软自己推荐的回复:

运行 .NET Core 控制台应用程序时,Visual Studio 使用不一致的工作目录。(请参阅 dotnet/project-system#3619)这会导致抛出异常:no such table: Blogs.要更新工作目录:

右键单击项目并选择编辑项目文件

在 TargetFramework 属性下方添加以下内容:

<StartWorkingDirectory>$(MSBuildProjectDirectory)</StartWorkingDirectory>

保存文件

现在您可以运行该应用程序:

调试 > 启动而不调试


Eri*_*kEJ 6

EF6的SQLite提供程序不支持"代码优先/迁移"工作流,因此您必须在EF6工作流之外手动创建数据库.


Kay*_*Kay 5

这篇文章激发了我的Code First方法的工作:
使用Entity Framework Core Code First创建SQLite DB

诀窍是要在上下文构造函数中调用sureCreated:

    public MediaContext()
    {
        Database.EnsureCreated();
    }
Run Code Online (Sandbox Code Playgroud)

关于表名与属性名的匹配:
您可以使用该Table属性使事情起作用:

public DbSet<MediaModel> Media { get; set; }
Run Code Online (Sandbox Code Playgroud)

并在模型类中显式指定表名,尽管这似乎很多余:

[Table("MediaModel")]
public class MediaModel
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用带有 new SqliteConnection("DataSource=:memory:") 连接的迁移,那么迁移将被忽略,您必须使用“Database.EnsureCreated()”。谢谢+1 (2认同)

Gre*_*che 3

就像 ErikEJ 所说的那样,SQLite 不首先以我使用的方式支持代码,显然它有严格的命名策略。

为了使这一切正常工作,我必须手动创建表,并使上下文适应命名模式(Media=> MediaModels)。

语境

public DbSet<MediaModel> MediaModels { get; set; }
Run Code Online (Sandbox Code Playgroud)

达尔

public DataAccessLayer(string path)
{
    _path = Path.GetFullPath(path);
    _connectionPath = _path + @"\MyDatabase.sqlite";
    
    using (var db = new MediaContext(_connectionPath))
    {
        db.Database.ExecuteSqlCommand("CREATE TABLE IF NOT EXISTS 'MediaModels' ('Name' TEXT, 'FilePath' TEXT NOT NULL PRIMARY KEY, 'Tags' TEXT, 'Note' TEXT, 'FileExtension' TEXT)");

        db.SaveChanges();
    }
}
    
public void Generate()
{
    using (var db = new MediaContext(_connectionPath))
    {
        db.MediaModels.Add(new MediaModel("test"));
        db.SaveChanges();
    }
}
Run Code Online (Sandbox Code Playgroud)

该代码仍然不完美,我会在改进时尝试更新这个答案。