2017-08-11 75 views
0

试图与WCF服务第一次使用EF 6码,但遇到了以下运行时错误:首先在EF6代码的WCF服务中设置DbConfiguration的位置?

The default DbConfiguration instance was used by the Entity Framework before the 'MyConfiguration' type was discovered. An instance of 'MyConfiguration' must be set at application start before using any Entity Framework features or must be registered in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information.

试图实例以下的DbContext服务调用内时,此错误被抛出:

[DbConfigurationType(typeof(MyConfiguration))] 
public partial class MyContext : DbContext 
{ 
    public MyContext() 
     : base("name=MyContext") 
    { 
    } 
} 

public class MyConfiguration : DbConfiguration 
{ 
    public MyConfiguration() 
    { 
     SetExecutionStrategy(MySqlProviderInvariantName.ProviderName,() => new MySqlExecutionStrategy()); 
     SetDefaultConnectionFactory(new MySqlConnectionFactory()); 
     AddDependencyResolver(new MySqlDependencyResolver()); 
    } 
} 

这个WCF服务还有其他的DbContexts在这个类甚至被访问之前使用,所以错误信息是非常有意义的。问题是应该在哪里设置配置?

+0

它应该在WCF服务的配置,作为最后它是应用程序,这是运行,从而具有有效的配置。请参考:[this](https://msdn.microsoft.com/en-us/library/jj556606(v = vs.113).aspx)和[this](https://stackoverflow.com/questions/20354083/ef6-and-multiple-configurations-sql-server-and-sql-server-compact) –

+0

删除'[DbConfigurationType(typeof(MyConfiguration))]'',再试一次。 –

+0

谢谢,问题似乎是由项目中已经创建的其他EF上下文引起的。将不得不做更多的研究来找出解决方案。 –

回答

0

上创建MyContext一个构造如下:

public MyContext(DbConnection dbConnection, bool contextOwnsConnection) 
    : base(dbConnection, contextOwnsConnection) 
{ 
} 

然后手动供给的MySqlConnection:

var connection = new MySqlConnection(connectionString); 
connection.Open(); 
var context = new MyContext(connection, true);