EF6 NOT NULL约束的基于文件的SQLite在插入时失败

时间:2018-09-16 18:27:35

标签: c# asp.net entity-framework sqlite

我想创建一个只能与.exe一起使用的程序,因此我需要从我的程序内部创建一个基于文件的数据库。我试图将SQLite与Entity Framework结合使用,所以我设置了以下类:

Program.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>

我尝试在Context构造函数中自行设置数据库(使用SQLiteConnectionSQLiteCommand),但是即使它成功创建了数据库和表,EF仍然给我同样的错误。当我注释掉构造函数时,它不会创建文件。

有没有办法实现我想要的?

2 个答案:

答案 0 :(得分:1)

您的连接字符串不完整。

SELECT atmno,MIN(atmid),SUM(netpay) FROM table 
where atmno is not null group by atmno
UNION ALL
SELECT atmno,atmid,netpay FROM table WHERE atmno IS NULL

初始目录应包含您的数据库名称。数据源只是实例名称。

答案 1 :(得分:1)

您应该使用System.Data.SQLite的{​​{1}} instad。提供者将使用Microsoft的托管SQLite包装项目System.Data.SqlClient而不是Microsoft.Data.SQLite项目。

System.Data.SQLite

将此构造函数添加到您的数据库上下文类中,因为有时默认构造函数无法正常工作。

<connectionStrings>
<add name="MyContext"
      connectionString="Data Source=|DataDirectory|db.sqlite"
      providerName="System.Data.SQLite" />
</connectionStrings>

希望它对您有用。