jason
jason

Reputation: 7164

How does AttachDbFilename work?

This may be a stupid question. But I have to ask. I'm making an ASP.NET MVC 5 application with EF code-first. I can't understand how AttachDbFilename work. Does this create and attach a database to database instance? Or does it just attach an existing database? Do I really need to use it if the database already attached? For example, here is my default connection string :

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication3-20150205041122.mdf;Initial Catalog=aspnet-WebApplication3-20150205041122;Integrated Security=True"
      providerName="System.Data.SqlClient" />

And I have a context named "ShoesContext". When I check localdb, I see both "aspnet-WebApplication3-20150205041122" and "ShoesContext".

I want to achieve the same for a remote server. How should I change my connection string? Should I copy and attach "aspnet-WebApplication3-20150205041122" to my remote database instance? Or should I do something else? Thanks.

Upvotes: 0

Views: 388

Answers (1)

Izzy
Izzy

Reputation: 6866

To change your connectionString to a remote server you will have to do

<connectionStrings>
<add name="myConnectionString" connectionString="server=myServer;database=myDb;uid=myUser;password=myPass;" providerName="System.Data.SqlClient" />
</connectionStrings>

<connectionStrings>
<add name="mySecondConnectionString" connectionString="server=myServer;database=myDb;uid=myUser;password=myPass;" providerName="System.Data.SqlClient" />
</connectionStrings>

You C# Code will look like

var firstConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
var secondConnectionString = ConfigurationManager.ConnectionStrings["mySecondConnectionString"].ConnectionString;

Further info here

Upvotes: 1

Related Questions