Using EntityFramework 6 Part 2: Database Connections

This post is part of a mini series on using EntityFramework (EF). If you do not have EF installed go to Part 1: Introduction and Setup to see what (basic) steps we took to get EF installed.
In this part we are going to use Code-First methods to start model building, then eventually connecting to the database . This is not the only way and you do not have to do things in exactly the same order as I have but if you follow along you should have a working version at the end.

Database
Firstly, create a database at your preferred location. Once you have a database add the connection string to the web.config file. I added a database to the App_Data folder so this is what the connectionsString definition look like in my web.config file.

  <connectionStrings>
    <add name="DBConn" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DB.mdf;Integrated Security=True"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

Next, add a class which inherits from DBContext. An instance of DBContext, LibraryDBContext in this example, is used to perform CRUD operations against a database. To read up on DBContext see these articles
http://www.entityframeworktutorial.net/EntityFramework4.3/dbcontext-vs-objectcontext.aspx

namespace WebApplication2.Models
{
    public class LibraryDBContext:DbContext
    {
        public LibraryDBContext() : base("DBConn")
        { }

        public DbSet<Book>Books{ get; set; }
    }
}

This gives sufficient Entity Framework code to enable our application to access a database.

The Model
Now we will start the model by creating a Book entity. Create a Book class in the Models folder of your application.

namespace WebApplication2.Models
{
    public class Book
    {
        public int BookId { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
    }
}

Following Code-First conventions, because we have defined an property called BookId (class name ‘Book’ plus ‘Id’) Entity Framework will nominate this property as an identity column when the database tables are generated. If we had a property simply named Id, Entity Framework would have nominated that as the identity and created an identity column called Id.

Displaying Book Info
Add a Controller to the application, I have called it BooksController. The Index action retrieves all the books from what will be the Books table.

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class BooksController : Controller
    {
          public ActionResult Index()
        {
            var books = new List<Book>();
            using (var db = new LibraryDBContext())
            {
                books = db.Books.ToList();
            }
            return View(books);
        }
    }
}

The last code related change is to create a View for the Index Action to display all the books.

@model IEnumerable<WebApplication2.Models.Book>
    @Html.ActionLink("Create New", "Create")
<table class="table">
<tr>
<th>
            @Html.DisplayNameFor(model => model.Author)</th>
<th>
            @Html.DisplayNameFor(model => model.Title)</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
            @Html.DisplayFor(modelItem => item.Author)</td>
<td>
            @Html.DisplayFor(modelItem => item.Title)</td>
<td>
            @Html.ActionLink("Edit", "Edit", new { id=item.BookId }) |
            @Html.ActionLink("Details", "Details", new { id=item.BookId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.BookId })</td>
</tr>
}</table>

Running the Application
The application should build at this point. Currently we have a database that contains no tables. If you run the application now The database/tables will only be created/modified on a read/write action. So run the application and navigate to your controller (e.g. \books). Because the Index action of the Books controller contains code that retrieves data via the inherited DBContext class, and because Entity Framework knows there are models with no corresponding database table, the tables will be created with columns types that match the model properties.

Using EntityFramework 6 Part 1: Introduction and Setup

In this mini series we will be looking at how to implement EntityFramework 6 (from now on referred to as EF) into an MVC application, primarily using Code First methods. In this first part we are going to set up our project.  If you already have a project ready skip to the Setup EF section. If you already have EF version 6 installed feel free to go to part 2: Putting Database Connections into Context.

New MVC Project

I was going to lay out the steps required to create a new project. However, I assume you are able to complete that without step-by-step instructions. Depending on which options you select when creating a new project will determine whether you need to install EF. If you selected an internet application with individual user accounts then EF will have been installed during project creation with a DataContext used for user authentication.

Setup EntityFramework
There are two primary ways to install a NuGet package. By using PowerShell commands in the Package Manager Console or by using a visual interface.
To use the Package Manager Console go to Tools > Nuget Package Manager > Package Manager Console. At the NuGet command line enter this command to install EF

Install-Package EntityFramework -projectname DemoApplication

The -projectname switch forces EF to be installed in a specific project. If you have only one project in your solution you can omit the parameter and use

Install-Package EntityFramework

Either way you should see a message confirming EF has been successfully installed.

To use the visual interface go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution… to open the interface.  On the left select Online and in the search box on the right enter entity framework.

nuget-entityframework6

I already have EF installed which is why you see a green circle with a tick.  If it is not installed then you will see an install button.
Once you have EF installed you are ready to continue.