In this exercise you will learn how to use the Code First approach to add a database with the tables of the MusicStore application to consume its data.
Once adding the database and generating the model, you will make the proper adjustments in the StoreController to provide the View template with the data taken from the database instead of hardcoding it.
Note: |
|---|
| If you have completed Exercise 1 and have already worked with Database Approach, you will now learn how to get the same results with a different process. Some tasks will be repeated with Exercise 1, so they are marked appropriately to make your reading easier. If you have not completed Exercise 1 but would like to learn the Code First approach, you can start from this exercise and get a full coverage of the topic. |
Task 1 – Adding a database
In this task you will add an already created database with the main tables of the MusicStore application to the solution.
Note: |
|---|
| This task is in common with Exercise 1. |
- Start Microsoft Visual Web Developer 2010 Express from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Web Developer 2010 Express.
- In the File menu, choose Open Project. In the Open Project dialog, browse to Source\ Ex02-AddingADatabaseCodeFirst\Begin, select MvcMusicStore.sln and click Open.
- Add an App_Data folder to the project to hold the SQL Server Express database files. App_Data is a special folder in ASP.NET which already has the correct security access permissions for database access. To add the folder, right-click MvcMusicStore project, select Add, Add ASP.NET folder and finally App_Data.
- Add MvcMusicStore database file. In this hands-On Lab, you will use an already created database called MvcMusicStore.mdf. To do that, right-click the new App_Data folder, select Add and then Existing Item. Browse to \Source\Assets\ and select the MvcMusicStore.mdf file.

Figure 2
Adding an Existing Item
Figure 3
MvcMusicStore.mdf database file - The database has been added to the project. Even when the database is located inside the solution, you can query and update it as it was hosted in a different database Server.

Figure 4
MvcMusicStore database in Solution Explorer - Verify the connection to the database. To do this, select the Database Explorer, and then double-click the MvcMusicStore.mdf. The connection is established.

Figure 5
Connecting to MvcMusicStore.mdf
Note:if you get an error like the following, please follow the steps below. 
1. Open the Windows Services console. To do that, open the Run command from Start | All Programs | Accessories | Run, type services.msc and then click OK.
Figure 27
Running services.msc
2. Right-click the SQL Server (SQLEXPRESS) service and select Properties.
Figure 28
SQL Server (SQLEXPRESS) service
3. Open the Log On tab, select Local System account as the account to log on with and click OK. Accept the dialog by clicking OK again.
Figure 29
Changing the log on account
4. Restart the SQL Server (SQLEXPRESS) service. - Close the connection now. To do that, right-click on the MvcMusicStore database and select Close Connection.

Figure 32
Closing the connection

Figure 1
Adding an App_Data folder
Note: |
|---|
![]() Figure 30 Restarting SQL Server (SQLEXPRESS) service 5. Once the service is restarted, close the Services console and verify the connection to the database. To do this, select the Database Explorer, and then double-click the MvcMusicStore.mdf. The connection is established. ![]() Figure 31 Connecting to MvcMusicStore.mdf |
Task 2: Including Code First in the solution and connecting the database
Now that we have already added a database to our project, we will write in the Web.Config the connection string. Then will include an external library for Entity Framework 4 Code First.
Note: |
|---|
| If you completed Exercise 1, you will note that these steps were automatically generated by a wizard. As Code First is not providing a wizard, you will have to implement many of them manually. |
- Add a connection string at Web.Config. To do that, open Web.Config at project root and include these lines at the end of the file:

Figure 6
Web.Config file locationXML
Copy Code
… <connectionStrings> <add name="MusicStoreEntities" connectionString="data source=.\SQLEXPRESS;initial catalog=MvcMusicStore;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MvcMusicStore.mdf;User instance=true" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>
- Add a new reference to the Code First library Microsoft.Data.Entity.CTP.dll. To do that, right click on “References”, “Add Reference”:

Figure 7
Adding a reference - Browse to Source\Assets\EntityFrameworkCTP4 and select “Microsoft.Data.Entity.CTP.dll”. Then, click OK:

Figure 8
Adding Microsoft.Data.Entity.CTP library 
Figure 9
Library Added to the project
Task 3: Working with the model
Now that we have already included code first library and connected the database, we will link the model with the database tables. In this task, we will create a class that will be linked to the database with Code First. Remember we already have a POCO model class that should be modified.
Note: |
|---|
| If you completed exercise 1, you will note that this step was performed by a wizard. By doing code first, you will manually create classes that will be linked to data entities. |
- Open the POCO model class Genre from /Models project folder and include an ID and a description attribute.
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First Genre– CSharp)
C#
Copy Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcMusicStore.Models { public class Genre { public int GenreId { get; set; } public string Name { get; set; } public string Description { get; set; } } }
Note:To work with Code First conventions, Genre must have a primary key property that will be automatically detected.You can read more about Code First Conventions in this msdn blog article. - Right click the Models project folder and select Add and then Class to add a new class. Name it MusicStoreEntities.cs and click Add.

Figure 10
Adding a class 
Figure 11
Adding a class(2)- Open the class you have just created, MusicStoreEntities.cs, and Include the namespace System.Data.Entity
C#
Copy Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; …
- Replace the class declaration to extend DbContext class: declare a public DBSet and override the method OnModelCreating. After this step you will get a domain class that will link your model with the Entity Framework. In order to do that, replace the class code with the following:
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First MusicStoreEntities– CSharp)
C#
Copy Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MvcMusicStore.Models { public class MusicStoreEntities : DbContext { public DbSet<Genre> Genres { get; set; } protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) { modelBuilder.IncludeMetadataInDatabase = false; modelBuilder.Entity<Genre>().MapSingleType().ToTable("Genre"); base.OnModelCreating(modelBuilder); } } }
Note:
With Entity Framework DbContext and DBSet you will be able to query the POCO class Genre.
By extending OnModel Creating we are specifying in the code how Genre will be mapped to a database table.
You can find more information about DBContext and DBSet in this msdn blog article: link
Task 4: Querying the database
In this task you will update the StoreController so that instead of using hard-coded data, it can consume it from the database.
Note: |
|---|
| This task is in common with Exercise 1. If you completed Exercise 1 you will note these steps are the same, independently from the approach (Database first or Code first). They are different in how the data is linked with the model, but the access to data entities has to be the transparent from the controller. |
- Open Controllers\StoreController.c s and add the following field to hold an instance of the MusicStoreEntities class, named storeDB:
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First storeDB – CSharp)
C#
Copy Code
public class StoreController : Controller { MusicStoreEntities storeDB = new MusicStoreEntities(); - The MusicStoreEntities class exposes a collection property for each table in the database. Update StoreController’s Index action to retrieve all Genre names in the database. This was done previously by hard-coding string data. Now you can instead write a LINQ query expression like the one below which retrieves the Name property of each Genre within the database:
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 code First Store Index – CSharp)
C#
Copy Code
// // GET: /Store/ public ActionResult Index() { // Retrieve the list of genres var genres = from genre in storeDB.Genres select genre.Name; // Create your view model }
Note:You are using a capability of .NET called LINQ (language-integrated query) to write strongly-typed query expressions against these collections – which will execute code against the database and return objects that you can program against.
For more information about LINQ, please visit the msdn site.- Transform the collection of genres to a list. To do this, replace the following code:
(Code Snippet – ASP.NET MVC Models and Data Access – Ex2 Code First Genres to List – CSharp)
C#
Copy Code
public ActionResult Index() { // Retrieve the list of genres var genres = from genre in storeDB.Genres select genre.Name; // Create your view model var viewModel = new StoreIndexViewModel { Genres = genres.ToList(), NumberOfGenres = genres.Count() }; return View(viewModel); }
Task 4: Running the application
In this task, you will check that the Store Index page will now display the Genres stored in the database instead of the hard-coded ones. There is no need of changing the View template because the StoreController is returning the same StoreIndexViewModel as before, although this time the data will come from the database.
- Press F5 to run the Application.
- The project starts in the Home page. Change the URL to /Store to verify that the list of Genres is no longer the hard-coded list, else the ones taken from the database.

Figure 12
Browsing Genres from the database

