c# - 在发现 'EFConfiguration' 类型之前使用的 DbConfiguration 实例

标签 c# entity-framework-6

在我的 MVC4 应用程序中,我引用了我的 EF 模型程序集。一切正常。突然之间,我开始收到以下错误消息。

The default DbConfiguration instance was used by the Entity Framework before the 'EFConfiguration' type was discovered. An instance of 'EFConfiguration' 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.

我正在使用 EF 6。知道可能是什么原因吗?我仔细检查数据库及其更新并与 EF dll 同步。

更新:我在尝试实例化 Context 对象时收到此错误

mEntities context = new Entities();

谢谢

最佳答案

我只想为那些有类似错误消息的人留下解决方案。作为link来自 Vinicius Paiva,它清楚地解释了如果您在不同的 dll 中有多个 dbcontex,如果您在代码中创建了一个,则应该引用您的 DbConfiguration 文件。 在我的例子中,我有 azure functions 项目引用 DAL 项目,获得 azure functions 项目的唯一方法是创建部分类和基于代码的 DbConfiguration 文件。

所以用下面的代码扩展我的 edmx 文件 DbContext

namespace myApp.Data.Models
{
    [DbConfigurationType(typeof(myDBContextConfig))]
    partial class myDBEntities
    {

        public myDBEntities(string connectionString) : base(connectionString)
        {
        }
    }

      public  class myDBContextConfig : DbConfiguration
        {
            public myDBContextConfig()
            {
                SetProviderServices("System.Data.EntityClient", 
                SqlProviderServices.Instance);
                SetDefaultConnectionFactory(new SqlConnectionFactory());
            }
        }
    }

这个 DAL 库引用了一个 MVC 项目,我们有另一个 edmx 实例。所以当我运行这个项目时,它抛出了这个异常。为了解决这个问题。您需要在配置文件中扩展或添加 entityFramework 节点(在本例中为 web.config)

<entityFramework codeConfigurationType="myApp.Data.Models.myDBContextConfig , myApp.Data">
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework> 

关于c# - 在发现 'EFConfiguration' 类型之前使用的 DbConfiguration 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31151271/

相关文章:

c# - 输入鼠标位置没有准确捕获?

c# - Log4Net 不释放资源

c# - 无法读取 Entity Framework 中的系统 View

c# - 获取适用于 EF6 的最新版本 MySQL

asp.net-mvc-5 - 如何使用 StructureMap、MVC 5 和 WebApi 2 注册每个请求依赖项?

c# - Microsoft 服务管理器控制台 API?

C# 如何将数组中的每个元素添加到 XML 树中的子节点?

c# - 在 .net Compact Framework 中使用 WEB API 身份验证

c# - 如何更改类型验证错误消息?

.net - EF 6.0.0 - 不从头开始创建数据库