c# - 没有 App.config 的 SQLite Entity Framework

标签 c# .net entity-framework sqlite app-config

有必要对 3d 方应用程序插件使用 SQLite Entity Framework 数据库优先方法。我搜索了所有互联网,包括Add a DbProviderFactory without an App.Config , Problems using Entity Framework 6 and SQLite和许多其他。我尝试以不同的方式和组合使用它们,但没有任何帮助:

"An unhandled exception of type 'System.Data.Entity.Core.MetadataException' occurred in mscorlib.dll. Additional information: Schema specified is not valid. Errors: AutosuggestModel.ssdl (2,2): error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SQLite.EF6'. Make sure the provider is registered in the 'entityFramework' section of the application config file."

解决方案中有一个测试控制台应用程序。有了这个最小的 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>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <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>

连接字符串已经在代码中实现了。使用的包是:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.3" targetFramework="net452" />
  <package id="System.Data.SQLite" version="1.0.98.1" targetFramework="net452" />
  <package id="System.Data.SQLite.Core" version="1.0.98.1" targetFramework="net452" />
  <package id="System.Data.SQLite.EF6" version="1.0.98.1" targetFramework="net452" />
  <package id="System.Data.SQLite.Linq" version="1.0.98.1" targetFramework="net452" />
</packages>

请提供所有必需的代码并指定插入位置。提前致谢。

最佳答案

这是一个示例代码,说明了如何实现目标。

namespace SqliteEFNoConfig
{
    using System.Configuration;
    using System.Data;
    using System.Data.Common;
    using System.Data.Entity;
    using System.Data.Entity.Core.Common;
    using System.Data.SQLite;
    using System.Data.SQLite.EF6;
    using System.Linq;

    internal class Program
    {
        private static void Main()
        {
            // EF manages the connection via the DbContext instantiation
            // connection string is set in config
            // Use this code if you want to use a config file
            // with only the connection string
            //using (var model = new Model1())
            //{
            //    var dbSetProperty = model.dbSetProperty.ToList();
            //}

            // Alternative method: 
            // Use this code if you don't want to use a config file
            // You will also need to use the override constructor shown below,
            // in your EF Model class
            var connectionString = @"data source = {PathToSqliteDB}";
            using (var connection = new SQLiteConnection(connectionString))
            {
                using (var model = new Model1(connection))
                {
                    var dbSetProperty = model.dbSetProperty.ToList();
                }
            }
        }
    }

    class SqliteDbConfiguration : DbConfiguration
    {
        public SqliteDbConfiguration()
        {
            string assemblyName = typeof (SQLiteProviderFactory).Assembly.GetName().Name;

            RegisterDbProviderFactories(assemblyName );
            SetProviderFactory(assemblyName, SQLiteFactory.Instance);
            SetProviderFactory(assemblyName, SQLiteProviderFactory.Instance);
            SetProviderServices(assemblyName,
                (DbProviderServices) SQLiteProviderFactory.Instance.GetService(
                    typeof (DbProviderServices)));
        }

        static void RegisterDbProviderFactories(string assemblyName)
        {
            var dataSet = ConfigurationManager.GetSection("system.data") as DataSet;
            if (dataSet != null)
            {
                var dbProviderFactoriesDataTable = dataSet.Tables.OfType<DataTable>()
                    .First(x => x.TableName == typeof (DbProviderFactories).Name);

                var dataRow = dbProviderFactoriesDataTable.Rows.OfType<DataRow>()
                    .FirstOrDefault(x => x.ItemArray[2].ToString() == assemblyName);

                if (dataRow != null)
                    dbProviderFactoriesDataTable.Rows.Remove(dataRow);

                dbProviderFactoriesDataTable.Rows.Add(
                    "SQLite Data Provider (Entity Framework 6)",
                    ".NET Framework Data Provider for SQLite (Entity Framework 6)",
                    assemblyName,
                    typeof (SQLiteProviderFactory).AssemblyQualifiedName
                    );
            }
        }
    }
}

如果您决定在配置文件中添加连接字符串,那么您需要在 EF 模型中添加以下构造函数。

public Model1(DbConnection connection)
    : base(connection, true)
{
}

注意:以上代码只是实现目标的示例,您需要根据自己的需要进行相应的调整。假设您使用的是 EF Code First 方法,则提供上述代码。

关于c# - 没有 App.config 的 SQLite Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32319930/

相关文章:

C#:抽象类需要实现接口(interface)?

c# - 如何用多个表填充数据集?

.net - 窗体的 InvokeRequired == false 和包含的控件的 InvokeRequired == true

c# - 如果 modelstate 无效,则 Action Filter 不会运行

c# - 是否可以将 [XmlAttribute] 作为类的默认值?

c# - Azure表: Fetch without create a specific class or knowing the whole schema

c# - .NET IExtenderProvider (C#)

entity-framework - Entity Framework 5.0 Beta - 是否会提供 DbContext 代码生成模板?

c# - EF 4.3 关系不正确

entity-framework - Linq 到实体和 Xml 字段