public class EntityFrameworkConfiguration : DbConfiguration
{
public EntityFrameworkConfiguration()
{
this.SetModelCacheKey(ctx => new EntityModelCacheKey((ctx.GetType().FullName + ctx.Database.Connection.ConnectionString).GetHashCode()));
}
}
为了使上面的代码工作,我在 web.config 中添加了下面一行
但是对于我使用程序集引用的其他项目,我遇到了异常:
{"The default DbConfiguration instance was used by the Entity Framework before the 'EntityFrameworkConfiguration' type was discovered. An instance of 'EntityFrameworkConfiguration' 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."}
最佳答案
您的问题没有说明您如何使用此自定义 DbConfiguration。
您可能会通过几种不同的方式获得此错误。
配置样式设置
如此处所述:Entity Framework Config File Settings
配置即代码
如此处所述:Entity Framework Code-Based Configuration (EF6 onwards)
您可以通过像 DbConfiguration.SetConfiguration(xxxx) 这样的操作来破解
这种风格。我觉得这根本没用。
这真正归结为您如何构建 DbContext。
配置文件样式构造函数 https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/DbContext.cs#L75 没有参数 - EF6 使用配置文件来确定要使用的正确 DbCofniguration
再次使用一些“类似连接字符串”的参数,EF6 使用配置文件来确定 DbConfiguration
没有配置或错误的配置 - 你会得到这种类型或异常
作为代码风格构造器的配置 https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/DbContext.cs#L139
我认为这会产生更好的控制。
属性你的 DbContext,然后使用手动创建的 DbConnection
public class EntityFrameworkConfiguration : DbConfiguration
{
public EntityFrameworkConfiguration()
{
this.SetModelCacheKey(ctx => new EntityModelCacheKey((ctx.GetType().FullName + ctx.Database.Connection.ConnectionString).GetHashCode()));
}
}
[DbConfigurationType(typeof(EntityFrameworkConfiguration))]
public class MyContext : DbContext
{
public MyContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{ }
public DbSet<Stuff> Stuff { get; set; }
}
using(var conn = new SqlConnection(asqlserverConnectionString))
using (var db = new MyContext(conn, true))
{
var value = await db.Stuff.Where(s => s.xxx.Equals(primaryKey)).Select(s => new { s.BinaryContent } ).SingleOrDefaultAsync();
}
关于c# - 在发现 'EntityFrameworkConfiguration' 类型之前使用了默认的 DbConfiguration 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32177785/