【发布时间】:2018-09-16 18:27:34
【问题描述】:
我想创建一个仅可与 .exe 一起使用的程序,因此我需要从我的程序内部创建一个基于文件的数据库。我正在尝试将 SQLite 与实体框架一起使用,因此我设置了以下类:
程序.cs
class Program
{
static void Main(string[] args)
{
using (MyContext context = new MyContext())
{
context.Documents.Add(new Document() { Id = 1, CategoryId = 2, Description = "test", Keywords = "test,TEST,", Text = "TEST test Test" });
Console.WriteLine(context.Documents.Single(x => x.Id == 1).Text);
Console.ReadKey();
}
}
}
class MyContext : DbContext
{
public DbSet<Document> Documents { get; set; }
}
class Document
{
public int Id { get; set; }
public int CategoryId { get; set; }
public string Text { get; set; }
public string Keywords { get; set; }
public string Description { get; set; }
}
在运行代码时,它会抛出这个异常:
Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName
但据我所知,我在 app.config 中正确指定了连接字符串:
<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.6.1" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="MyContext" connectionString="Data Source=db.sqlite" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
我尝试在上下文构造函数中自行设置数据库(使用SQLiteConnection 和SQLiteCommand),但即使它成功创建了数据库和表,EF 仍然给我同样的错误。当我注释掉构造函数时它不会创建文件。
有没有办法实现我想要的?
【问题讨论】:
-
我对 SQLite 了解不多。但是您是否可能需要提供 db 文件的确切路径?获取信息来自:damienbod.com/2015/08/30/… 和 connectionstrings.com/sqlite
-
配置文件中的所有内容都适用于 SQL Server。您是否通过 NuGet 安装了 Sqlite 连接器?
-
@GertArnold 是的,我尝试了
Microsoft.Data.SQLite和System.Data.SQLite
标签: c# asp.net entity-framework sqlite