没有App.config的SQLite实体框架

时间:2015-08-31 21:03:08

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

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

  

“未处理的类型异常   mscorlib.dll中发生'System.Data.Entity.Core.MetadataException'。   附加信息:指定的模式无效。错误:   AutosuggestModel.ssdl(2,2):错误0152:没有实体框架提供程序   找到具有不变名称的ADO.NET提供程序   'System.Data.SQLite.EF6'。确保提供商已注册   应用程序配置文件的“entityFramework”部分。“

解决方案中有一个测试控制台应用程序。使用这个最小的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>

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

1 个答案:

答案 0 :(得分:4)

以下示例代码说明了如何实现目标。

from django.db.models import Max

MyClass.objects.values('my_integer').annotate(Max('created_ts'))

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

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 Code First方法,则提供上述代码。