EF6和多个配置(SQL Server和SQL Server Compact) [英] EF6 and multiple configurations (SQL Server and SQL Server Compact)

查看:156
本文介绍了EF6和多个配置(SQL Server和SQL Server Compact)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:问题已解决,请参阅此问题的结尾。



问题



我们试图在一个场景中使用Entity Framework 6和基于代码的配置,我们在同一个 AppDomain中使用了SQL Server和SQL Server CE, / code>。



这个相当简单的场景似乎不被设计支持。从EF团队:


注意:我们不支持在
中使用多个配置类同一个AppDomain。如果您使用此属性为两个上下文设置不同的
配置类,将抛出异常。


更多信息: 基于代码的配置(Codeplex)



问题



我们如何从这里前进?任何帮助将不胜感激!有没有更灵活的方式来将配置连接到上下文而不是 AppDomain



(我们的上下文类我们已经尝试了 DbConfigurationType 属性,但问题是EF本身)



配置文件:



正常SQL Server的配置

  public class EfConfiguration:DbConfiguration 
{
public EfConfiguration()
{
SetProviderServices(
SqlProviderServices.ProviderInvariantName,
SqlProviderServices.Instance);

SetDefaultConnectionFactory(new SqlConnectionFactory());
}
}

SQL Server Compact Edition的配置

  public class EfCeConfiguration:DbConfiguration 
{
public EfCeConfiguration()
{
SetProviderServices(
SqlCeProviderServices.ProviderInvariantName,
SqlCeProviderServices.Instance);

SetDefaultConnectionFactory(
new SqlCeConnectionFactory(SqlCeProviderServices.ProviderInvariantName));
}
}

更新: p>

我们得到的错误是:


System.TypeInitializationException:
'MyProject.Repositories.Base.DataContext'
抛出一个异常。 ----> System.InvalidOperationException:设置了一个'efCeConfiguration'的
实例,但这个类型不是在与'DataContext'上下文相同的程序集中被发现的

将DbConfiguration类型放在与DbContext
类型相同的程序集中,在DbContext类型上使用DbConfigurationTypeAttribute到
指定DbConfiguration类型,或者将
中的DbConfiguration类型设置为config文件。请参见 http://go.microsoft.com/fwlink/?LinkId=260883&hl=zh_CN
更多信息。


更新2,解决方案
如上所述,我们只能有一个配置。这是一个问题,因为Sql和SqlCe使用不同的提供程序。如果我们使用SetDefaultConnectionFactory来适应一种类型的数据库,另一种将会失败。



而是将连接提供到上下文中,如标题为answer 。一旦您总是使用连接初始化上下文,而不是连接字符串,那么您很好。您可以从配置中删除SetDefaultConnectionFactory调用。我们仅使用以下代码来配置SqlCe上下文,并且没有配置Sql上下文。

  public class CommonEfConfiguration:DbConfiguration 
{
public CommonEfConfiguration()
{
// EF不知道ce提供者是否默认为
//因此需要通知它。
//连接工厂不是必需的,因为连接
//始终在UnitOfWork类中创建
SetProviderServices(SqlCeProviderServices.ProviderInvariantName,SqlCeProviderServices.Instance);
}
}


解决方案

编辑:基于错误详细信息:
您是否已经尝试告诉EF找到配置类的位置?

  [DbConfigurationType MyNamespace.MyDbConfiguration,MyAssemblyFullyQualifiedName)] 
public class MyContextContext:DbContext
{
}

如果这样做不起作用,那么看另一个



使用Context与构造函数DbConnection



public class MYDbContext:DbContext {
//在MyMigrationsContextFactory

中管理MIgration无参数构造函数public MyDbContext(string connectionName):base(connectionName) {} // no this

public MYDbContext(DbConnection dbConnection,bool contextOwnsConnection)// THIS ONE
:base(dbConnection,contextOwnsConnection){}

然后需要一个DBConnectionconnecti为每个提供商。
对于SQL服务器

  public DbConnection GetSqlConn4DbName(string dataSource,string dbName){
var sqlConnStringBuilder = new SqlConnectionStringBuilder();
sqlConnStringBuilder.DataSource = String.IsNullOrEmpty(dataSource)? DefaultDataSource:dataSource;
sqlConnStringBuilder.IntegratedSecurity = true;
sqlConnStringBuilder.MultipleActiveResultSets = true;

var sqlConnFact = new SqlConnectionFactory(sqlConnStringBuilder.ConnectionString);
var sqlConn = sqlConnFact.CreateConnection(dbName);
return sqlConn;
}

为SqlCe工厂重复,它也可以生成一个DBConnection
< a href =http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.sqlceconnectionfactory.createconnection%28v=vs.113%29.aspx =noreferrer> SqlCe连接因素创建连接


Update: Problem solved, see end of this question.

The problem:

We are trying to use Entity Framework 6 and code-based configuration in a scenario were we have use both a SQL Server and SQL Server CE in the same AppDomain.

This quite simple scenario seems not to be supported "by design". From the EF team:

Note: We do not support having multiple configuration classes used in the same AppDomain. If you use this attribute to set different configuration classes for two contexts an exception will be thrown.

More information here: Code-based Configuration (Codeplex)

The question:

How do we move forward from here? Any help would be greatly appreciated! Is there a more flexible way to connect a configuration to a context instead of an AppDomain?

(Our context classes are located in different assemblies. We have tried the DbConfigurationType attribute but the problem is EF itself)

Configuration files:

Configuration for normal SQL server

public class EfConfiguration : DbConfiguration
{
    public EfConfiguration()
    {
        SetProviderServices(
            SqlProviderServices.ProviderInvariantName, 
            SqlProviderServices.Instance);

        SetDefaultConnectionFactory(new SqlConnectionFactory());
    }
}

Configuration for SQL Server Compact Edition

public class EfCeConfiguration : DbConfiguration
{
    public EfCeConfiguration()
    {
        SetProviderServices(
            SqlCeProviderServices.ProviderInvariantName,
            SqlCeProviderServices.Instance);

        SetDefaultConnectionFactory(
            new SqlCeConnectionFactory(SqlCeProviderServices.ProviderInvariantName));
    }
}

UPDATE:

The error which we get is:

System.TypeInitializationException : The type initializer for 'MyProject.Repositories.Base.DataContext' threw an exception. ----> System.InvalidOperationException : An instance of 'EfCeConfiguration' was set but this type was not discovered in the same assembly as the 'DataContext' context. Either put the DbConfiguration type in the same assembly as the DbContext type, use DbConfigurationTypeAttribute on the DbContext type to specify the DbConfiguration type, or set the DbConfiguration type in the config file. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information.

UPDATE 2, the solution As described above, we can only have one configuration. This is a problem since Sql and SqlCe uses different providers. If we use "SetDefaultConnectionFactory" to fit one type of database, the other will fail.

Instead, supply the connection into the context as described in the post marked as answer below. Once you always initialize the context with a connection as opposed to a connectionstring you are good to go. You can remove the SetDefaultConnectionFactory call from the configuration. We're using only the code below for configuring the SqlCe Context and no configuration for the Sql Context.

  public class CommonEfConfiguration : DbConfiguration
    {
        public CommonEfConfiguration()
        {
            // EF does not know if the ce provider by default,
            // therefore it is required to be informed about it.
            // The connection factories are not necessary since the connection
            // is always created in the UnitOfWork classes
            SetProviderServices(SqlCeProviderServices.ProviderInvariantName, SqlCeProviderServices.Instance);
        }
    }

解决方案

EDIT: based On Error details: Did you already try tell EF where the config class is found?

[DbConfigurationType("MyNamespace.MyDbConfiguration, MyAssemblyFullyQualifiedName")]
public class MyContextContext : DbContext
{
}

If that cant be made work, then see alternative

Use the Context with constructor DbConnection

public class MYDbContext : DbContext {
     // MIgration parameterless constructor is managed in  MyMigrationsContextFactory 

    public MyDbContext(string connectionName) : base(connectionName) { } // no this

    public MYDbContext(DbConnection dbConnection, bool contextOwnsConnection)  // THIS ONE
        : base(dbConnection, contextOwnsConnection) {  }

you then need a "DBConnection" connection for each provider. For SQL server

      public DbConnection GetSqlConn4DbName(string dataSource, string dbName) {
        var sqlConnStringBuilder = new SqlConnectionStringBuilder();
        sqlConnStringBuilder.DataSource = String.IsNullOrEmpty(dataSource) ? DefaultDataSource : dataSource;
        sqlConnStringBuilder.IntegratedSecurity = true;
        sqlConnStringBuilder.MultipleActiveResultSets = true;

        var sqlConnFact = new SqlConnectionFactory(sqlConnStringBuilder.ConnectionString);
        var sqlConn = sqlConnFact.CreateConnection(dbName);
        return sqlConn;
    }

repeat for SqlCe factory, it can also generate a DBConnection SqlCe connection factor create connection

这篇关于EF6和多个配置(SQL Server和SQL Server Compact)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆