【问题标题】:Unknown Connection String Executing未知的连接字符串正在执行
【发布时间】:2018-08-10 02:21:54
【问题描述】:

我已经清楚地说明了我需要我的 MVC 应用程序在 Web Config 文件中使用的连接字符串:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="OnlineStoreDB" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=OnlineStoreDB; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|OnlineStoreDB.mdf" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <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>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

但是当我运行这个应用程序时,出现以下运行时错误:

Cannot attach the file 'D:\Visual Studio Projects\OnlineStore\OnlineStore\App_Data\DefaultConnection.mdf' as database 'DefaultConnection'.

我很难在我的应用程序中到处找到DefaultConnection,但没有任何用处。

谁能帮我看看后台发生了什么。

提前致谢。

更新

我在文件IdentityModels.cs 中找到了以下代码,其中包含此名称DefaultConnection。不确定它到底在做什么:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public System.Data.Entity.DbSet<OnlineStore.Models.Item> Items { get; set; }
    }

Context文件代码:

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Microsoft.AspNet.Identity.EntityFramework;
using OnlineStore.Models.MvcMusicStore.Models;

namespace OnlineStore.Models
{
    public class OnlineStoreDB : IdentityDbContext
    {
        public OnlineStoreDB()
            : base("OnlineStoreDB")
        {
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
        }
        public DbSet<Item> Items { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Brand> Brands { get; set; }
        public DbSet<Cart> Carts { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
        public System.Data.Entity.DbSet<OnlineStore.ViewModels.ShoppingCartViewModel> ShoppingCartViewModels { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
        }
    }
}

请注意,我从IdentityDBContext 派生Context 类(OnlineStoreDB)而不是DBContext,因为我需要在我的应用程序中使用IdentityRoles

【问题讨论】:

  • 确认 MDF 文件可用?
  • 或者有什么特殊原因在连接字符串中提到了MDF文件?
  • 这是猜测:您使用的是什么用户/登录管理代码?如果它是作为项目模板的一部分生成的,则可能需要您指定要用作用户数据库的内容。只需查看该代码即可。
  • @PrashantPimpale。我故意删除了“DefaultConnection.mdf”,只是因为我不想让我的应用使用它。我想知道它为什么会去那里。
  • 父 web.config 文件中是否还有其他连接字符串?通过针对该名称(即DefaultConnection)搜索整个项目来找出使用的连接字符串。

标签: c# sql asp.net-mvc


【解决方案1】:

您需要将ApplicationDbContext 构造函数中的DefaultConnection 更改为您自己的连接密钥(即OnlineStoreDB),如下所示:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("OnlineStoreDB", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public System.Data.Entity.DbSet<OnlineStore.Models.Item> Items { get; set; }
}

请注意,ApplicationDbContext 构造函数期望从其IdentityDbContext 构造函数提供的连接字符串中加载数据库定义,并且由于没有与具有键DefaultConnection 的连接关联的连接字符串(和数据库文件),因此引发了错误。

补充说明:

听起来你当前的连接字符串应该修改为这个:

<add name="OnlineStoreDB" connectionString="Data Source=(localdb)\MSSQLLocalDB; 
     Initial Catalog=OnlineStoreDB;Integrated Security=True; 
     MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|\OnlineStoreDB.mdf" 
     providerName="System.Data.SqlClient" />

【讨论】:

  • 应用您建议的更改后,在 localDB 上创建了一个带有 OnlineStoreDB 的数据库,但问题是它只有一个名为 dbo.__MigrationHistory 的表,并且没有任何 ASP.NET 实体被转换为SQL 数据库表。我正在将“上下文”文件代码添加到我的问题中以供您查看。谢谢
  • 由于您有 EF Code First 上下文定义,因此您需要启用迁移以添加现有数据库架构(使用 Enable-MigrationAdd-Migration,然后使用 Update-Database)。您可以阅读步骤here(注意:迁移过程似乎与此问题所要求的问题不同)。
  • 我注意到您建议的连接字符串中的 \OnlineStoreDB.mdf 与我的连接字符串中使用的 OnlineStoreDB.mdf 不同。我应用了您的代码,但很抱歉,它没有任何区别。
  • [\] 反斜杠符号标记数据库文件的路径(它遵循操作系统路径约定)。在您可以将现有数据库与 Code First 一起使用之前(注意 OnModelCreating 的用法),有必要如前所述启用迁移。
  • 我应用了 Migrations,现在它的所有工作都像魅力一样。非常感谢兄弟在整个过程中的帮助。赞赏。
猜你喜欢
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 2021-10-13
  • 2015-10-14
  • 2014-04-24
  • 2011-04-27
相关资源
最近更新 更多