0

I've clearly stated what connection string I need my MVC application to use in Web Config file:

<?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>

But when I'm running this app, following runtime error is occuring:

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

I've looked very hard to find DefaultConnection everywhere in my app, but nothing to avail.

Can anyone please help me find out what's goin on in the background.

Thanks in advance.

Update

I found this following code in file IdentityModels.cs which has this name DefaultConnection in it. Not sure what exactly its doing:

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 file code:

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>();
        }
    }
}

Please note that I'm deriving Context class (OnlineStoreDB) from IdentityDBContext instead of DBContext because I need to use IdentityRoles in my app.

  • Have checked that MDF file is available? – Prashant Pimpale Aug 10 '18 at 02:25
  • Or any special reason ti mention the MDF file nane in connection string? – Prashant Pimpale Aug 10 '18 at 02:25
  • This is guesswork: what user/login management code are you using? If it was generated as part of a project template, it might require you to specify what to use as the user database. Just look through that code. – Andrew Shepherd Aug 10 '18 at 02:28
  • @PrashantPimpale. I've deliberately deleted 'DefaultConnection.mdf` simply because I don't want my app to use it. I'm wondering why its even going there. –  Aug 10 '18 at 02:32
  • @AndrewShepherd, That's what. Where exactly to find code for this `DefaultConnection` connectionstring ... I tried hard to find it in my app, but no good. –  Aug 10 '18 at 02:34
  • @PrashantPimpale When I'm clearly telling it to use a connectionstring given in the web.config, where do you think it's picking up settings for 'DefaultConnection` connectionstring from? –  Aug 10 '18 at 02:52
  • 1
    Are there other connection strings inside parent web.config file? Find out where the connection string used by searching entire project against that name (i.e. `DefaultConnection`). – Tetsuya Yamamoto Aug 10 '18 at 03:19
  • can you share your webconfig file? – farrukh aziz Aug 10 '18 at 04:27
  • @TetsuyaYamamoto: I've updated my question. –  Aug 10 '18 at 04:51
  • @farrukhaziz: Done. –  Aug 10 '18 at 04:51
  • @Dad have a look at :https://stackoverflow.com/a/17031891/7124761 – Prashant Pimpale Aug 10 '18 at 05:30
  • @PrashantPimpale, my question is not about attaching .mdf to my app. I've updated my question. Please go through it. Currently problem I'm facing is: `Context` I'm trying to use is only generating `dbo.__MigrationHistory` in the database and none from the `DBSets` entities are getting translated into SQL tables. –  Aug 10 '18 at 05:33

1 Answers1

1

You need to change DefaultConnection in ApplicationDbContext constructor to your own connection key (i.e. OnlineStoreDB) like this:

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; }
}

Note that ApplicationDbContext constructor expects loading database definitions from provided connection string from its IdentityDbContext constructor, and since no connection string (and database file) associated with connection which has key DefaultConnection the error was thrown.

Additional note:

Sounds like your current connection string should be modified to this one:

<add name="OnlineStoreDB" connectionString="Data Source=(localdb)\MSSQLLocalDB; 
     Initial Catalog=OnlineStoreDB;Integrated Security=True; 
     MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|\OnlineStoreDB.mdf" 
     providerName="System.Data.SqlClient" />
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • After applying your suggested changes, a database with `OnlineStoreDB` is made on localDB but problem is that it has only 1 table in it named `dbo.__MigrationHistory` and none of the ASP.NET entities are translated into SQL database tables. I'm adding 'Context` file code to my question for your review. Thank you –  Aug 10 '18 at 05:16
  • 1
    Since you have EF Code First context definition, you need to enable migrations for adding existing DB schema (with `Enable-Migration` and `Add-Migration`, then `Update-Database`). You can read the steps [here](https://msdn.microsoft.com/en-us/library/dn579398(v=vs.113).aspx) (note: the migration process seem to be different issue than this question asked for). – Tetsuya Yamamoto Aug 10 '18 at 05:38
  • I noticed `\OnlineStoreDB.mdf` in your suggested connection string differs to `OnlineStoreDB.mdf` used in my connection string. I applied your code but sorry, it isn't making any difference. –  Aug 10 '18 at 05:40
  • The `[\]` backslash sign marks path to the database file (it follows OS path convention). Before you can use that existing DB with Code First (notice that `OnModelCreating` usage), it is necessary to enable migrations as mentioned before. – Tetsuya Yamamoto Aug 10 '18 at 05:54
  • I applied Migrations and its all working now like a charm. Thanks alot bro for your help throughout. Appreciated. –  Aug 10 '18 at 05:59