Friday, June 22, 2012

Northwind-mania: Reading Categories table using MVC 3.0, Entity Framework, and KnockoutJS

This lesson demonstrates how one can easily display the contents of the Categories table in the Northwind database on a web page using KnockoutJS:

Pre-requisites:

  • Visual Studio 2010
  • MVC 3.0
  • Northwind database
  • SQL Server Express
  • NuGet

Step 1:

In Visual Studio click: File >> New Project. On the next dialog choose: Web >> ASP.NET MVC 3.0 web application and give your application a decent name as shown below:

image

Step 2:

On the next screen, choose “Internet Application”.

image

Step 3:

In Solution Explorer, right-click on Reference and select “Manage NuGet Packages …”.

image

Step 4:

Enter “knockout” in the search field on the top right-hand-side of the next screen. Select “knockoutjs” then click on the “Install” button.

image

The knockoutjs JavaScript file will be contained in your project in the Scripts directory:

image

Step 5:

Right-click on the “Models” folder: Add >> New Item:

image

Add an “ADO.NET Entity Data Model (Visual C#)” item named “NorthwindModel.edmx”:

image

Select “Generate from database” then click “Next”.

image

Choose the appropriate Northwind database connection then click Next.

image

Click on the checkbox beside Tables, then click the “Finish” button.

image

Step 6:

Replace the Index() action in the HomeController.cs with the following code:

public ActionResult Index() {
   using (NorthwindEntities ctx = new NorthwindEntities()) {
       var categories = from c in ctx.Categories
                        select new { c.CategoryID, c.CategoryName };

       ViewBag.Categories = categories.ToList();

       return View();
   }
}

Step 7:

Open the index.cshtml file in the Views/Home directory. Drag and drop the “knockout-2.1.0.js” from the Scripts folder into the index.cshtml file above the <h2> tag. This produces the <script> tag pointing to the JavaScript file.

Step 8:

Replace the contents of the <p>..</p> section with the following:

<ul data-bind="foreach: categories">    
    <li><span data-bind="text: $data.CategoryName"></span></li>
</ul>
<script type="text/javascript">   
    var viewModel = {        
        categories: @Html.Raw(Json.Encode(ViewBag.Categories))    
    };   
    ko.applyBindings(viewModel);
</script>

Step 9:

Run the application by hitting F5. You should see the following web page:

image

If you look at the page view source, you should notice the following JSON data in the <script> section:

<script type="text/javascript">   
  var viewModel = {        
      categories: [
         {"CategoryID":1,"CategoryName":"Beverages"},
         {"CategoryID":2,"CategoryName":"Condiments"},
         {"CategoryID":3,"CategoryName":"Confections"},
         {"CategoryID":4,"CategoryName":"Dairy Products"},
         {"CategoryID":5,"CategoryName":"Grains/Cereals"},
         {"CategoryID":6,"CategoryName":"Meat/Poultry"},
         {"CategoryID":7,"CategoryName":"Produce"},
         {"CategoryID":8,"CategoryName":"Seafood"}
      ]    
  };   
  ko.applyBindings(viewModel);
</script>

Thursday, June 7, 2012

Northwind-mania: Generating a strongly-typed DbContext class + persistence ignorant classes from the Northwind Entity Framework model

In this lesson you will learn how to create simple domain classes from the Northwind EDMX Entity Framework model.

Pre-requisites:

  • Visual Studio 2010
  • Entity Framework 4.1 or later
  • ASP.NET MVC 3.0 or later
  • Northwind database

Step 1:

Download and install the EF 4.x DbContext Generator for C# into your Visual Studio 2010.

Step 2:

Start Visual Studio 2010 and create a new project based on the “ASP.NET MVC 2 Web Application” project type.

image

Select the Internet Allocation template.

image

Step 3:

Add an Entity Framework model for your Northwind database. This is done as follows:

Right-click your Models folder and choose Add >> New Item. Select “ADO.NET Entity Data Model” and name it NorthwindModel.edmx.

image

On the  next dialog, select “Generate from Database” then click on “Next”.

image

Select your appropriate data connection to the Northwind database then click Next.

image

Select all tables by clicking on the checkbox beside Tables then click on Finish.

image

Compile your application with Shift + CTRL + B so that your classes become visible to your project.

Step 4:

Right-click anywhere on your model and select “Add Code Generation …”.

image

If you have installed the EF 4.x DbContext Generator for C# in step 1 above, you will see the EF 4.x DbContext Generator option. Select that option. give the model the name NorthwindModel.tt then click on the Add button.

image

You may see a security warning. Click on the checkbox beside “Do not show this message again”

image

The simple POCO domain classes are created together with the DbContext class.

image

Let us first take a peek at one of the smallest domain classes, the Region entity.

public partial class Region {
  public Region() {
      this.Territories = new HashSet<Territory>();
  }

  public int RegionID { get; set; }
  public string RegionDescription { get; set; }

  public virtual ICollection<Territory> Territories { get; set; }
}

Note how very simple the Region class is. Next, let us look at the DbContext class file named NorthwindModel.Context.cs.

public partial class NorthwindEntities : DbContext {
  public NorthwindEntities() : base("name=NorthwindEntities") { }

  protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      throw new UnintentionalCodeFirstException();
  }

  public DbSet<Category> Categories { get; set; }
  public DbSet<CustomerDemographic> CustomerDemographics { get; set; }
  public DbSet<Customer> Customers { get; set; }
  public DbSet<Employee> Employees { get; set; }
  public DbSet<Order_Detail> Order_Details { get; set; }
  public DbSet<Order> Orders { get; set; }
  public DbSet<Product> Products { get; set; }
  public DbSet<Region> Regions { get; set; }
  public DbSet<Shipper> Shippers { get; set; }
  public DbSet<Supplier> Suppliers { get; set; }
  public DbSet<Territory> Territories { get; set; }
}

Since we do not need the EDMX model anymore, go ahead and delete NorthwindModel.edmx file.

Conclusion:

This post shows you how you can take an Entity Framework EDMX model and create from it a simple POCO model based on the DbContext class.