Search code examples
asp.net-mvcentity-frameworkclass-library

Class library using Entity Framework DbContext


I have two ASP.NET MVC5 projects, I want to connect them to the same database. I created a class library that contains the models and the DbContext.

The first app connects correctly, but when I run the second one I get an error says :

Cannot attach the file 'c:\users\saibi\documents\visual studio 2015\Projects\MonPFE\MonPFE.Frontend\App_Data\MonPFEContext-20161121115318.mdf' as database 'MonPFEContext-20161121115318'

PS: I have web.config in each project.


Solution

  • Make sure you have the same connection string in each Web.config and that they point to the same database. Beware that relative paths for AttachDbFilename will point at different directories.

    I'm betting you have Connection Strings that look something like this:

    <connectionStrings>
        <add name="MonPFEContext" connectionString=".\SQLExpress;AttachDbFilename=|DataDirectory|MonPFEContext.mdf; Database=MonPFEContext;Trusted_Connection=Yes;" providerName="System.Data.SqlClient"/>
      </connectionStrings>
    

    |DataDirectory| will typically be the App_Data folder in each web project. The database file exists in one web application, but not the other. Update AttachDbFilename to point to a full file path, or use a relative path to the same file.