Adding Entityframework Data Access To A Project

Most new projects require some sort of data access method. I used the following steps with an MVC application in Visual Studio 2013, they should be enough to get you started. I am going to assume you have already have an MVC ready project open. To keep the code snippets short not all the namespace references are shown, just the key ones.

Setup the Database
It is up to you what type of database you use, SQLExpress, SQL Server or something else. Create a database and set the permissions as needed, most likely for development you will use integrated security.
For starters add a table to hold product data with the below script.

CREATE TABLE Products
(
    [ProductID] INT NOT NULL PRIMARY KEY IDENTITY,
    [ProductCode] NVARCHAR(100) NOT NULL,
    [Description] NVARCHAR(500) NOT NULL,
    [UnitPrice] DECIMAL(9, 2) NOT NULL
)

For now populate the table with some dummy data.

INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P1234', 'Torch', 23.99)
INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P3456', 'Toaster', 15.90)
INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P7890', 'Football', 10.00)
INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P1037', 'Hair Net', 3.50)
INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P1634', 'Cooker', 156.99)

Creating a table in the database is actually optional, if you go full Code-First and don’t create a table it will be created automatically by the DBInitializer on the first call requiring the table when the application is run. Just be aware that there will not be any data in the table initially.

Setup EntityFramework
Open the Package Manager Console by going to Tools > Nuget Package Manager > Package Manager Console. At the NuGet command line enter this command to install EntityFramework

Install-Package EntityFramework -projectname DemoApplication

the -projectname switch forces EntityFramework to be installed in a specific project. If you have only one project in your solution you could use

Install-Package EntityFramework

Create a Domain Model

  • In your application right-click the Models folder and select Add > Class… (Ctrl+Shift+A).
  • In the Add New Item dialog, select Class from the template list and enter a suitable name for your class e.g. Product.cs
  • Select the Add button
  • Edit the class with the properties you need
    namespace DemoApplication.Models
    {
        public class Product
        {
            public int ProductID { get; set; }
            public string ProductCode { get; set; }
            public string Description { get; set; }
            public decimal UnitPrice { get; set; }
        }
    }
    

Create a DBContext Class

  • In your application right-click the Models folder and select Add > Class… (Ctrl+Shift+A).
  • In the Add New Item dialog, select Class from the template list and enter a suitable name for your DBContext class e.g. EFDBContext.cs
  • Select the Add button
  • Edit the class similar to this
    using System.Data.Entity;
    
    namespace DemoApplication.Models 
    {
        public class EFDbContext : DbContext 
        {
            public DbSet<Product> Products { get; set; }
        }
    }
    

    The name of the property Products is the name of the table Entityframework will access. The type specified in the DBSet is the object Entityframework will populate.

Add a Connectionstring to Config
The connection string will depend on which database you connected to. AS I was using SQL Server my connectoin string looks similar to this.

<connectionStrings>
    <add name="EFDbContext" connectionString="Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

Create a Repository

  • First of all an interface, In your application right-click the Models folder and select Add > New Item… (Ctrl+Shift+A).
  • In the Add New Item dialog, select Interface from the template list enter a suitable name for your repository interface e.g. IProductRepository.cs
  • Select the Add button
  • Edit the repository interface
    using SportsStore.Domain.Entities;
    namespace DemoApplication.Models
    {
        public interface IProductRepository
        {
            IEnumerable<Product> Products { get; }
        }
    }
    
  • Next, the concrete Repository class. In your application right-click the Models folder and select Add > New Item… (Ctrl+Shift+A).
  • In the Add New Item dialog, select Class from the template list enter a suitable name for your repository e.g. EFProductRepository.cs
  • Select the Add button
  • Edit the ProductRepository class as below
    using System.Collections.Generic;
    
    namespace DemoApplication.Models 
    {
        public class EFProductRepository : IProductRepository 
        {
            private EFDbContext context = new EFDbContext();
            public IEnumerable<Product> Products 
            {
                    get { return context.Products; }
            }
        }
    }
    

Controller Setup
In your controller, add a Product Repository

using DemoApplication.Models;

namespace DemoApplication.Controllers
{
    public class ProductController : Controller
    {
        private IProductRepository repository;

        public ProductController()
        {
            this.repository = new ProductRepository;
        }

        public ViewResult Index() 
        {
            return View(repository.Products);
        }      
    }
}

Controller Setup
The very last thing to do is set up the view to display a list of products.

@model IEnumerable<DemoApplication.Models.Product>
@{
 ViewBag.Title = "Products";
}
<table>
@foreach (var product in Model) {
<tr>
<td>@product.ProductCode</td>
<td>@product.Description</td>
<td>@product.UnitPrice.ToString("c")</td>
</tr>
}</table>

This is a bit of a whirlwind tour but hopefullly enough information to get a project going in accessing data with Entityframework.

Javascript IntelliSense in Visual Studio

IntelleSense is a pretty standard feature of any modern Integrated Development Environment (IDE). Visual Studio has the ability to display IntelleSense not only for the whole .Net framework but also for any libraries included in the solution and any custom code written in C#, VB or similar language. IntelliSense is not available for javascript files by default, partly because javascript is not build by a compiler. Fortunately it is quite easy to configure.
Firstly, create a new file called _references.js in the ‘Script’ folder of your project (note the intended leading underscore). Then add a reference for each file you require IntelliSense for like below;

/// <reference path="jquery-2.1.1.js" />
/// <reference path="knockout-3.2.0.debug.js" />
/// <reference path="your-custom-file.js" />

There is a shortcut to typing the references manually, simply drag and drop the file from the Solution Explorer into the editor pane and the reference will be added for you.

That’s basically it. Simple but useful.

Switching Microsoft Account User In Visual Studio 2013

A while ago I installed a 30 day trial of VS2013 Premium. At the time I used my personal email to create a Microsoft account and used that to sign in to VS2013. Some time later my MSDN license was renewed and one of the first things I did was to download and install VS2013. The fact there had been a previous installation was recognised and the same Microsoft account was referenced, so when I tried to log in with my normal MSDN Microsoft account VS promptly diaplayed the folling message.

We were unable to establish the connection because it is configured for user but you attempted to connect using user. To connect as a different user perform a switch user operation. To connect with the configured identity just attempt the last operation again.

There have been a few reported method to fix this issue

1. Sign in as a different user:
Click on your name in the upper right corner and click on “Account settings”.
This will give you the option to sign out.
Once signed out you can sign back in as another Microsoft account.

2. Via the registry:
Deleting the following registry key
hkey_current_user\software\Microsoft\VSCommon\12.0\clientservices\tokenstorge\visualstudio\ideuser

In my case I was not able to log in with the old account as between the aforementioned ‘while ago’ and ‘some time later’ I had deleted the Microsoft account referencing my personal email address, it no longer existed. Personally I preferred not to delete registry unless there was no other way. So I ended up using a third option to resolve this by following the suggestion in the VS dialog, and that was to switch user.

3. Switching User:

  1. Exit Visual Studio
  2. Start the Developer Command Prompt for 2013 installed with Visual Studio in the Visual Studio Tools folder. Ensure you right click and select Run as administrator.
  3. At the command prompt type ‘devenv /resetuserdata’
  4. You can now start Visual Studio as Normal.

If you are using the VS2013 Express you will need to replace devenv with the name of the executable. Now when VS2013 opened I was able to sign in with my other Microsoft account.