c# - 在发现 'EntityFrameworkConfiguration' 类型之前使用了默认的 DbConfiguration 实例

标签 c# .net entity-framework

 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/

相关文章:

c# - 动画化 UserControl XAML

c# - 在单个项目中使用多个平台

c# - Entity Framework Core 相关数据

entity-framework - 每个表中的列名必须是唯一的。表 'StripeRecipientId' 中的列名 'dbo.Foos' 被指定多次

c# - 在 C# 中复制二维数组

c# - 如何避免 .NET 中从 Unix 时间戳转换为 DateTime 并返回的精度损失?

javascript - 如何在 asp.net 中显示下拉列表的所有项目?

c# - 小型集合中 linq 和 INTERSECT/EXCEPT 的低性能

c# - CAKE 中的加载指令可以用于可选文件吗?

c# - 显示名称为 'VJSharpCodeProvider' 的程序集加载失败