Search code examples
winformsvisual-studio-2010entity-frameworkmdf

The most efficient way to replacing local database with .mdf file (project with Entity Model)


In my project I'm using Entity Framework and from the start I created the Model from a local database. Now I want to use a .mdf file (in the project directory) instead of a local database, but I want to do this with as little interference in the project as possible.

If it is possible I don't want to create a new Model or changing the Entity name and so on. What is the most efficient way to do this? Can I just change the connection string? And if yes, what should I change it to?


Solution

  • Just copy the mdf file to your AppData directory and change the connection to look like this:

    <add name="CONNECTION-NAME" connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBM‌​odel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=NAME-OF-MY-COMPUTER\sqlexpress;AttachDbFilename=|DataDirectory|\MyDBFile.mdf;Initial Catalog=DATABASE-NAME;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
    

    Note this part: AttachDbFilename=|DataDirectory|\MyDBFile.mdf;