-1

I followed this tutorial when learning SQL Azure and completed it successfully: Windows Azure Tutorial

I wanted to create a similar application but implement a more complex database using the code first approach and upon typing the 'update-database' command I am getting the following error:

Cannot attach the file 'c:\users\dadler\documents\visual studio 2012\Projects\EliteTrainingAzure\EliteTrainingAzure\App_Data\EliteTrainingAzure.Models.EliteTrainingDB.mdf' as database 'EliteTrainingAzure.Models.EliteTrainingDB'.

Here is my connection string:

 <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EliteTrainingAzure-20130325095843;User Intance = True;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EliteTrainingAzure-20130325095843.mdf" providerName="System.Data.SqlClient"/>

And finally here is an example of how I handled the Foreign Key Creation:

namespace EliteTrainingAzure.Models

{ public class Client { [Key] public int ClientID { get; set; }

    public int GoalID { get; set; }
    [ForeignKey("GoalID")]
    public Goal Goal { get; set; }

    public int TrainerID { get; set; }
    [ForeignKey("TrainerID")]
    public Trainer Trainer { get; set; }

    public string ClientName {get; set;}
    public string ClientAddress { get; set; }
    public string ClientCity { get; set; }
    public string ClientState { get; set; }
    public string ClientZip { get; set; }

If anyone could point me in the right direction as to how to fix this error that would be great. Thanks in advance!

tereško
  • 58,060
  • 25
  • 98
  • 150
Dadles
  • 119
  • 1
  • 1
  • 10
  • 1
    Does this help at all? http://stackoverflow.com/questions/13001441/delete-mdf-file-from-app-data-causes-exception-cannot-attach-the-file-as-databa – twoleggedhorse Mar 25 '13 at 20:04

1 Answers1

2

I have the same issue from time to time on a local project.

Though I've not yet determined the cause, this seems to be a workaround:

Rename the Initial Catalog and the .mdf file to new value and run Update-Database again.

E.g.:

...Initial Catalog=aspnet-EliteTrainingAzure-20130325095843;...

To

...Initial Catalog=aspnet-EliteTrainingAzure-xxx;...

And

...AttachDBFilename=|DataDirectory|\aspnet-EliteTrainingAzure-20130325095843.mdf"

To

...AttachDBFilename=|DataDirectory|\aspnet-EliteTrainingAzure-xxx.mdf"

It also seems to work to restore the connection string to the original naming, and rename the actual .mdf file.

Note: I don't know if this means that the underlying database system or the data migrations model database is getting cluttered with "orphaned" database references. The Update-Database process does not seem to have a problem with processing new names.

Note: Bear in mind that this is a workaround, not a solution. :)

Sigurd

Sigurd Garshol
  • 1,376
  • 3
  • 15
  • 36