Wednesday, May 27, 2015

Changing DefaultConnection to Sql Server DB in Auto generated MVC code

When "Internet Application" is chosen as template for MVC4 Web Application, we can see the auto generated code for the home page including user login logic. The tables will be created in the local DB instance in Visual studio in MDF file format as shown below.
But if you wish to store the data in your database in sql server, you have to make the following modifications.

1. Add your connection string in web.config file.

  <connectionstrings>

    <!-- <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Triczz-20150512151642;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-xxxx.mdf" providerName="System.Data.SqlClient" /> -->


   <add name="SomeConnectionName" connectionString="Data Source=.\SQLEXPRESS; Database=YourDB; Integrated Security=SSPI" providerName="System.Data.SqlClient" />


  </connectionStrings>


  
You can remove the "DefaultConnection" string commented above,

2. In AccountModels.cs, UsersContext uses "DefaultConnection".


Change "DefaultConnection" above to "YourDB" that you gave in web.config file. Or you can even pass the name of the connection string as :base(name="SomeConnectionName")

3. In WebSecurity.InitializeDatabaseConnection the connection name should be changed. It can be found in Global.asax or InitializeSimpleMembershipAttribute.cs in Filters folder.

Change the "DefaultConnection" to "SomeConnectionName" that you gave in web.config file.


Once the above changes are made, run the project to see the "UserProfile" and the other tables being created in the specified database.

No comments:

Post a Comment