【问题标题】:Connection String errors in C# Web ApiC# Web Api 中的连接字符串错误
【发布时间】:2017-11-02 10:17:52
【问题描述】:

我正在 C#.Net 中创建一个 Web Api。我已经使用 Unity.Mvc5 并使用 Db First 方法在其中实现了依赖注入。从那时起,我在连接字符串中遇到了一些问题。其中有一个默认的 AccountController,我创建了一个 TestController 来测试我的 Api。 我的 Web.config 文件中有两个连接字符串(其中一个已注释但只是为了显示此处我已取消注释)。

<add name="DDEXEntities" connectionString="Data Source=DESKTOP-CSB6551;initial catalog=DDEX;integrated security=True" providerName="System.Data.SqlClient" />
<add name="DDEXEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DESKTOP-CSB6551;initial catalog=DDEX;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

现在的问题是当我使用第一个字符串时,我的测试控制器 Api 不起作用。给出的例外是:

上下文在 Code First 模式下使用,代码是从 EDMX 文件生成的,用于 Database First 或 Model First 开发。这将无法正常工作。要解决此问题,请不要删除引发此异常的代码行。如果您希望使用 Database First 或 Model First,请确保 Entity Framework 连接字符串包含在启动项目的 app.config 或 web.config 中。如果要创建自己的 DbConnection,请确保它是 EntityConnection 而不是其他类型的 DbConnection,并且将其传递给采用 DbConnection 的基本 DbContext 构造函数之一。要了解有关 Code First、Database First 和 Model First 的更多信息,请参阅此处的实体框架文档:http://go.microsoft.com/fwlink/?LinkId=394715

当我使用第二个连接字符串时,我的帐户控制器不起作用并产生异常:

尝试创建类型为“AccountController”的控制器时出错。确保控制器有一个无参数的公共构造函数。

我的UnityConfig.cs如下:

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        container.RegisterType<DbContext, DDEXEntities>(new PerResolveLifetimeManager());
        // register all your components with the container here
        // it is NOT necessary to register your controllers

        container.RegisterType<AccountController>(new InjectionConstructor());

        // e.g. container.RegisterType<ITestService, TestService>();
        container.RegisterType<IGenreService, GenreService>(new TransientLifetimeManager());

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
    }
}

谁能告诉我我做错了什么。这让我很紧张。

提前致谢。

编辑 + 解决方案: 根据 Roman 的回答,我将我的第一个连接字符串命名为 DefaultConnection,并在 ApplicationDbContext 类构造函数中给出了这个 DefaultConnection。现在我的 AccountController 使用这个连接字符串,所有其他控制器都使用第二个连接字符串。 我希望它可以帮助某人。

【问题讨论】:

标签: c# entity-framework dependency-injection unity-container


【解决方案1】:

这是因为 AccountController 在 CodeFirst 模式下使用您的 DbContext。我认为最好使用单独的 DbContext:第一个仅用于身份验证和授权(在 CodeFirst 模式下),第二个用于其他东西(在 DatabaseFirst 模式下)。

您也可以尝试将 AccountController 配置为在 DatabaseFirst 模式下使用 DbContext。

【讨论】:

  • 你的回答给了我一个线索,所以 +1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2012-12-31
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多