Using Entity Framework with ASP.NET Web API 2 to build RESTful applications

ASP.NET Web API 2 is a framework for building RESTful applications on the .NET Framework. A broad range of clients, including browsers and mobile devices, can be built to process and present the data through HTTP web services.

In this post, I will build a basic web service by using ASP.NET Web API 2 template, reversed engineer the data model from existing database table by using Entity Framework 6, and finally scaffold and code the web service controller.

ASP.NET Web API template

Create a new project EmployeeWebAPI2 by using C# ASP.NET Application and Web API template in Microsoft Visual Studio 2013.

Reversed Engineering Model From Database

Here is the database schema in Microsoft SQL Server T-SQL.

Right Click on the project in Solution Explorer, and choose ‘Entity Framework – Reversed Engineering Code First’. Then connect to the instance (local) and database (test), and generate the model from test database for table ‘HR.Employees’. For more detail, please refer to my another post.

It will create testContext.cs, Employee.cs and EmployeeMap.cs. I commented out the key and relationship self reference to simply the object class.

Build Web Service Controller

Right Click on Controllers folder, and choose ‘Add->New Scaffold Item”. Choose ‘Web API 2 Controller with read/write Access’. Type ‘EmployeeController’ as controller name.

It will generate a EmployeeController.cs with a list of GET, POST, PUT and DELETE methods. The following steps show how to complete the various web URI methods using EF 6.

1. use the model generated from EF 6.

using EmployeeWebAPI2.Models;

2. GET api/employee

        // GET api/employee
        public IEnumerable<Employee> Get()
        {
            using (testContext entities = new testContext())
            {
                return entities.Employees.ToList<Employee>();
            }
        }

3. GET api/employee/5

        // GET api/employee/5
        public Employee Get(int id)
        {
            using (testContext entities = new testContext())
            {
                return entities.Employees.SingleOrDefault<Employee>(b => b.empid == id);
            }
        }

4. POST api/employee

        // POST api/employee
        public HttpResponseMessage Post(Employee value)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (testContext entities = new testContext())
                    {
                        entities.Employees.Add(value);
                        entities.SaveChanges();
                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.InternalServerError, "invalid New Value");
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

5. PUT api/employee/5

        // PUT api/employee/5
        public HttpResponseMessage Put(int id, Employee value)
        {
            try
            {
                using (testContext entities = new testContext())
                {
                    Employee myEmp = entities.Employees.SingleOrDefault<Employee>(b => b.empid == id);
                    // update all the fields
                    myEmp.empid = value.empid;
                    myEmp.lastname = value.lastname;
                    myEmp.firstname = value.firstname;
                    myEmp.title = value.title;
                    myEmp.titleofcourtesy = value.titleofcourtesy;
                    myEmp.birthdate = value.birthdate;
                    myEmp.hiredate = value.hiredate;
                    myEmp.address = value.address;
                    myEmp.city = value.city;
                    myEmp.region = value.region;
                    myEmp.postalcode = value.postalcode;
                    myEmp.country = value.country;
                    myEmp.phone = value.phone;
                    myEmp.mgrid = value.mgrid;
                    // flush to disk
                    entities.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

6. DELETE api/employee/5

        // DELETE api/employee/5
        public HttpResponseMessage Delete(int id)
        {
            try
            {
                using (testContext entities = new testContext())
                {
                    Employee myEmp = entities.Employees.SingleOrDefault<Employee>(b => b.empid == id);
                    entities.Employees.Remove(myEmp);
                    entities.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

Here is the complete code for EmployeeController.cs.

Test the web service

Build the solution and run the web service. Point your localhost url to:
http://localhost:55142/api/employee/2

It will get the following JSON object from url for (empid=2):


{"empid":2,"lastname":"Funk","firstname":"Don","title":"Vice President, Sales","titleofcourtesy":"Dr.","birthdate":"1962-02-19T00:00:00","hiredate":"2002-08-14T00:00:00","address":"9012 W. Capital Way","city":"Tacoma","region":"WA","postalcode":"10001","country":"USA","phone":"(206) 555-0100","mgrid":1}

I also use a tool called ‘Fiddler Web Debugger’ to examine the JSON / XML response return from the web service.

In the next post, I will write a client application to consume all the URIs in the above web api services.

Using Entity Framework in an ASP.NET MVC5 Application

In my previous two posts, I built a C# console application using Entity Framework (EF) in Microsoft Visual Studio 2013, and investigated how to perform CRUD operations on EF.

Building an ASP.NET MVC5 application using EF can become a straightforward job in Visual Studio 2013. It is very similar to building a J2EE MVC application by using JPA in Netbeans 7. The steps can be summarized as three steps: 1) create a ASP.NET MVC project; 2) add M: reversed engineer an EF model(M) from database; 3) Add C with V: scaffolding MVC 5 Controller (C) with views (V) using EF.

1. Create a ASP.NET MVC Project

In Microsoft Visual Studio 2013, create a new project (Ctrl-Shift-N) called EmployeeMVC using template (Visual C#->ASP.NET Web Application) and also select a template ‘MVC‘ and add folders and core references for ‘MVC’.

What will happene?
Visual Studio will create a few folders (App_Data, App_Start, Content, Controllers, fonts, Models, Scripts, Views) and files (Global.asax, packages.config, Web.config, Project_Readme.html, Startup.cs), also download a list of js scripts in Scripts folder, create AccountViewModels.cs and IdentityModels.cs in Models folder, AccountController.cs and HomeController.cs in Controllers folder, a list of *.shtml in various view folders, site style sheets in Contents folder and a few config.cs in App_Start.

Press F5 to build and run the empty application now.

2. Add ADO.NET Entity Data Model

Following the steps to reversed engineer EF 5 model from a table in the database into ASP.NET MVC (for reversed engineer an EF 6 model class, please use Entity Framework Power Tools):

  • Right click on Models folder, and choose New Item-Add->Data->ADO.NET Entity Data Model (C#);
  • Provide a Name: EmployeeModel.edmx and Click ‘Add’;
  • Choose ‘generate from database’ and Click ‘Next’
  • Connect to a SQL instance (local), choose your database (test) and table (HR.Employee)
  • If you receive a security warning, select OK to continue running the template.
  • This will add EmployeeModel.edmx (EF 5) as a folder under Models, and also add relevant references.

    Build the solution.

    3. Generate Controller and Views

    To generate controller and views:

  • Add the new controller to the existing Controllers folder. Right-click the Controllers folder, and select Add – New Scaffolded Item; Select the MVC 5 Controller with views, using Entity Framework option. This option will generate the controller and views for updating, deleting, creating and displaying the data in your model.
  • Set the controller name to EmployeeController, select Employee (EmployeeMVC.Models) for the model class, and select the testEntities (EmployeeMVC.Models) for the context class, Click ‘Add’
  • This will create EmployeeController.cs in Controllers:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using EmployeeMVC.Models;
    
    namespace EmployeeMVC.Controllers
    {
        public class EmployeeController : Controller
        {
            private testEntities db = new testEntities();
    
            // GET: /Employee/
            public ActionResult Index()
            {
                var employees = db.Employees.Include(e => e.Employee1);
                return View(employees.ToList());
            }
    
            // GET: /Employee/Details/5
            public ActionResult Details(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return HttpNotFound();
                }
                return View(employee);
            }
    
            // GET: /Employee/Create
            public ActionResult Create()
            {
                ViewBag.mgrid = new SelectList(db.Employees, "empid", "lastname");
                return View();
            }
    
            // POST: /Employee/Create
            // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
            // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create([Bind(Include="empid,lastname,firstname,title,titleofcourtesy,birthdate,hiredate,address,city,region,postalcode,country,phone,mgrid")] Employee employee)
            {
                if (ModelState.IsValid)
                {
                    db.Employees.Add(employee);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                ViewBag.mgrid = new SelectList(db.Employees, "empid", "lastname", employee.mgrid);
                return View(employee);
            }
    
            // GET: /Employee/Edit/5
            public ActionResult Edit(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return HttpNotFound();
                }
                ViewBag.mgrid = new SelectList(db.Employees, "empid", "lastname", employee.mgrid);
                return View(employee);
            }
    
            // POST: /Employee/Edit/5
            // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
            // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit([Bind(Include="empid,lastname,firstname,title,titleofcourtesy,birthdate,hiredate,address,city,region,postalcode,country,phone,mgrid")] Employee employee)
            {
                if (ModelState.IsValid)
                {
                    db.Entry(employee).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.mgrid = new SelectList(db.Employees, "empid", "lastname", employee.mgrid);
                return View(employee);
            }
    
            // GET: /Employee/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return HttpNotFound();
                }
                return View(employee);
            }
    
            // POST: /Employee/Delete/5
            [HttpPost, ActionName("Delete")]
            [ValidateAntiForgeryToken]
            public ActionResult DeleteConfirmed(int id)
            {
                Employee employee = db.Employees.Find(id);
                db.Employees.Remove(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
        }
    }
    
    

    It will also create a folder ‘Employee‘ in Views with a list of cshtml (Create, Delete, Details, Edit, Index)

    Build and run by pressing F5, and go to the similar link in the browser like:
    http://localhost:49481/employee

    I removed some of unwanted items in index.cshtml. My index page looked like:

    ASP.NET MVC 5 using EF

    ASP.NET MVC 5 using EF

    Summary

    Using Entity Framework, Visual Studio 2013 can easily generate a model from database, and scaffold a controller and generate all the views based on default templates and standard CRUD operations on EF.

    The advantage of this process is that the model, controller and view can be easily re-generated by repeating the above step 2 and 3 if the table structure in the underlying physical table is changed.

    The disadvantage is also obvious. Whatever customization made after the generation on (M. V. C) will have to be repeated after re-generation.

    Working With Model in Entity Framework

    In the previous post, I showed how to reversed-engineer an entity framework model from a Microsoft SQL Server 2012 database, and query the model in a C# console program. In the following, I will expand it further on how to work on the model generated to perform the standard CRUD (Create, Read, Update, Delete) operations.

    Model

    The model generated in the last post was in a file (testContext.cs) where the database context (testContext) was derived from DbContext, in which the property Employees was exposed as an entity (DbSet). In the simple RDBMS terms, the physical database (test) is mapped to DbContext (testContext) while a physical table (employees) was mapped to an entity DbSet (Employees). The entity model is like a conceptual model in the database design process.

    Little notes on database design process
    In a normal database design process, we design a conceptual model first by using designer like Visual Studio EF Designer or Oracle SQL developer/modeler, which will produce an ER-Diagram (Entity-Relationship Diagram) as a result. From the model, we can generate the physical model which is a set of DDLs, to run on a specific RDBMS like Oracle, MS SQL Server, etc. and produce a database.

    In our previous example, we reversed the design process from bottom up, and generated the conceptual model into Entity Framework in Visual Studio from the physical database structures in Microsoft SQL Server (Database: test; Table: HR.Employees). This process is called reversed engineering.

    namespace EmployeeConsole.Models
    {
        public partial class testContext : DbContext
        {
            ......
            public DbSet<Employee> Employees { get; set; }
            ......
        }
    }
    

    Work on Model

    To work on the model, the first is to include your model, then instantiate a dbContext so that the CRUD ops can be performed within the instance lifetime.

    Here is the code snippets. Refer to last post for details.

    using EmployeeConsole.Models;
    ...
          using (var db = new testContext())
              {
                 // TODO YOUR CRUD Ops
              }
    

    How to Read (Find) a Record

                using (var db = new testContext())
                {
    
                    var myemp = db.Employees.Find(3);
                    Console.WriteLine("Locate and Display empid=3");
                    Console.WriteLine("EmpID\t{0}",myemp.empid);
                    Console.WriteLine("FName\t{0}", myemp.firstname);
                    Console.WriteLine("LName\t{0}", myemp.lastname);
                    Console.WriteLine("HDate\t{0}", myemp.hiredate);
                    Console.WriteLine("Phone\t{0}", myemp.phone);
                    Console.WriteLine("Country\t{0}", myemp.country);
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                }
    

    How to Update a Record

                using (var db = new testContext())
                {
    
                    // Find the record first
                    var myemp = db.Employees.Find(3);
                    Console.WriteLine("EmpID\t{0}",myemp.empid);
                    Console.WriteLine("Firstname\t{0}", myemp.firstname);
                    Console.WriteLine("Lastname\t{0}", myemp.lastname);
    
                    // Update DbSet in memory
                    myemp.lastname = "Smith";
    
                    // Write to db
                    db.SaveChanges();
                    
                    // db.SaveChanges is the same as the following RAW T-SQL
                    //db.Database.ExecuteSqlCommand("update hr.employees set lastname='Smith' where empid=3");
    
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                }
    

    How to Add a New Record

                using (var db = new testContext())
                {
                    var newemp = new Employee();
                    newemp.firstname = "Adam";
                    newemp.lastname = "Smith";
                    newemp.title="Economist";
                    newemp.titleofcourtesy="";
                    newemp.birthdate=Convert.ToDateTime("01/01/1980");
                    newemp.hiredate=Convert.ToDateTime("01/01/2001");
                    newemp.address="16 Bay Street";
                    newemp.city="Toronto";
                    newemp.region="Mr.";
                    newemp.postalcode="B2C 2V7";
                    newemp.country="CANADA";
                    newemp.phone="(416) 822-2288";
    
                    // Add to DbSet
                    db.Employees.Add(newemp);
                    // Write to db
                    db.SaveChanges();
    
                    // db.SaveChanges is the same as the following RAW T-SQL
                    //db.Database.ExecuteSqlCommand("insert into hr.employees (..) values (...)");
    
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                }
    

    How to Delete a Record

                using (var db = new testContext())
                {
                    // identify the record first, (empid=10) is the new record inserted in last code snippet.
                    var empToBeDeleted=db.Employees.Find(10);
    
                    // remove from DbSet
                    db.Employees.Remove(empToBeDeleted);
    
                    // Write to db
                    db.SaveChanges();
    
                    // db.SaveChanges is the same as the following RAW T-SQL
                    //db.Database.ExecuteSqlCommand("delete from hr.employees where empid=10");
    
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                }
    

    Further Reading

  • Working with Entity Data from MSDN
  • Working with Objects
  • Working with Data (Entity Framework Tutorial)
  • Generate model from database using Entity Framework Power Tool

    The software I am using are:

    • Microsoft Visual Studion 2013 Premium
    • Microsoft SQL Server 2012 Enterprise
    • Entity Framework 6.0.1
    • Entity Framework Power Tools 1.0
    • Windows Server 2008 R2

    Create Database Objects

    I created a test database with a table HR.Employees as the following in my local Microsoft SQL 2012 instance (full T-SQL script is here):

    CREATE TABLE HR.Employees
    (
      empid           INT          NOT NULL IDENTITY,
      lastname        NVARCHAR(20) NOT NULL,
      firstname       NVARCHAR(10) NOT NULL,
      title           NVARCHAR(30) NOT NULL,
      titleofcourtesy NVARCHAR(25) NOT NULL,
      birthdate       DATETIME     NOT NULL,
      hiredate        DATETIME     NOT NULL,
      address         NVARCHAR(60) NOT NULL,
      city            NVARCHAR(15) NOT NULL,
      region          NVARCHAR(15) NULL,
      postalcode      NVARCHAR(10) NULL,
      country         NVARCHAR(15) NOT NULL,
      phone           NVARCHAR(24) NOT NULL,
      mgrid           INT          NULL,
      CONSTRAINT PK_Employees PRIMARY KEY(empid),
      CONSTRAINT FK_Employees_Employees FOREIGN KEY(mgrid)
        REFERENCES HR.Employees(empid),
      CONSTRAINT CHK_birthdate CHECK(birthdate <= CURRENT_TIMESTAMP)
    );
    

    Reversed Engineering DB Objects to Classes

    I created a simple C# console project called ‘EmployeeConsole’ in visual studio, which will create two files: Program.cs and App.config. Right Click on the project in Solution Explorer, and choose ‘Entity Framework – Reversed Engineering Code First’. Then connect to the instance (local) and database (test), and generate the model from test database for table ‘HR.Employees’.

    What Does Entity Framework Power Tool Do?

    1. Visual Studio first will install Entity Framework (runtime) into the project by creating packages.config as the following:

    <?xml version="1.0" encoding="utf-8"?>
    <packages>
      <package id="EntityFramework" version="6.0.1" targetFramework="net45" />
    </packages>
    

    2. Create model: a database context (testContext.cs)

    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using EmployeeConsole.Models.Mapping;
    
    namespace EmployeeConsole.Models
    {
        public partial class testContext : DbContext
        {
            static testContext()
            {
                Database.SetInitializer(null);
            }
    
            public testContext()
                : base("Name=testContext")
            {
            }
    
            public DbSet Employees { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Configurations.Add(new EmployeeMap());
            }
        }
    }
    

    3. Create model: a employees class in the model (Employee.cs)

    using System;
    using System.Collections.Generic;
    
    namespace EmployeeConsole.Models
    {
        public partial class Employee
        {
            public Employee()
            {
                this.Employees1 = new List();
            }
    
            public int empid { get; set; }
            public string lastname { get; set; }
            public string firstname { get; set; }
            public string title { get; set; }
            public string titleofcourtesy { get; set; }
            public System.DateTime birthdate { get; set; }
            public System.DateTime hiredate { get; set; }
            public string address { get; set; }
            public string city { get; set; }
            public string region { get; set; }
            public string postalcode { get; set; }
            public string country { get; set; }
            public string phone { get; set; }
            public Nullable mgrid { get; set; }
            public virtual ICollection Employees1 { get; set; }
            public virtual Employee Employee1 { get; set; }
        }
    }
    

    4. Create ORM: mapping POJO Employees class to physical table (EmployeeMap.cs) using Fluent API

    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.ModelConfiguration;
    
    namespace EmployeeConsole.Models.Mapping
    {
        public class EmployeeMap : EntityTypeConfiguration
        {
            public EmployeeMap()
            {
                // Primary Key
                this.HasKey(t => t.empid);
    
                // Properties
                this.Property(t => t.lastname)
                    .IsRequired()
                    .HasMaxLength(20);
    
                this.Property(t => t.firstname)
                    .IsRequired()
                    .HasMaxLength(10);
    
                this.Property(t => t.title)
                    .IsRequired()
                    .HasMaxLength(30);
    
                this.Property(t => t.titleofcourtesy)
                    .IsRequired()
                    .HasMaxLength(25);
    
                this.Property(t => t.address)
                    .IsRequired()
                    .HasMaxLength(60);
    
                this.Property(t => t.city)
                    .IsRequired()
                    .HasMaxLength(15);
    
                this.Property(t => t.region)
                    .HasMaxLength(15);
    
                this.Property(t => t.postalcode)
                    .HasMaxLength(10);
    
                this.Property(t => t.country)
                    .IsRequired()
                    .HasMaxLength(15);
    
                this.Property(t => t.phone)
                    .IsRequired()
                    .HasMaxLength(24);
    
                // Table & Column Mappings
                this.ToTable("Employees", "HR");
                this.Property(t => t.empid).HasColumnName("empid");
                this.Property(t => t.lastname).HasColumnName("lastname");
                this.Property(t => t.firstname).HasColumnName("firstname");
                this.Property(t => t.title).HasColumnName("title");
                this.Property(t => t.titleofcourtesy).HasColumnName("titleofcourtesy");
                this.Property(t => t.birthdate).HasColumnName("birthdate");
                this.Property(t => t.hiredate).HasColumnName("hiredate");
                this.Property(t => t.address).HasColumnName("address");
                this.Property(t => t.city).HasColumnName("city");
                this.Property(t => t.region).HasColumnName("region");
                this.Property(t => t.postalcode).HasColumnName("postalcode");
                this.Property(t => t.country).HasColumnName("country");
                this.Property(t => t.phone).HasColumnName("phone");
                this.Property(t => t.mgrid).HasColumnName("mgrid");
    
                // Relationships
                this.HasOptional(t => t.Employee1)
                    .WithMany(t => t.Employees1)
                    .HasForeignKey(d => d.mgrid);
    
            }
        }
    }
    

    5. Update App.config to include entity framework config and SQL connection string.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <connectionStrings>
        <add name="testContext" connectionString="Data Source=(local);Initial Catalog=test;Integrated Security=True;MultipleActiveResultSets=True"
          providerName="System.Data.SqlClient" />
      </connectionStrings>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
      </startup>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0" />
          </parameters>
        </defaultConnectionFactory>
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
    </configuration>
    

    Utilize your model

    The following is a simple program to display a list of employee records by using EmployeeConsole.Models which was defined in testContext.cs.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using EmployeeConsole.Models;
    
    namespace EmployeeConsole
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                using (var db = new testContext())
                {
                    // Get all the rows into var query by using LINQ if you want
                    //var query = from el in db.Employees orderby el.firstname select el;
    
                    // Get all the rows into var query by using SQL
                    var query = db.Employees.SqlQuery("select * from hr.employees");
    
                    // Display Listing Header
                    Console.WriteLine("LIST OF EMPLOYEES WITH PHONES:");
    
                    // just display firstnamelastnamephone
                    foreach (var item in query)
                    {
                        Console.WriteLine("{0}\t{1}\t{2}", item.firstname, item.lastname, item.phone);
                    }
    
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                }
            }
        }
    }
    

    Limitation on Processing Raw T-SQL queries

    What if when the SQL query changed to the following:

                select * from employees
                select firstname,lastname,phone from hr.employees
    

    Both are valid T-SQL queries, they won’t work from the model generated by Entity Framework because the model mapping has the following:

                this.ToTable("Employees", "HR");
                this.Property(t => t.empid).HasColumnName("empid");
    

    The execution will complain either no schema object ’employees’ in the first case or requiring ’empid’ in the latter.

    To use the model generated, it’s better to use either LINQ-TO-ENTITY or ENTITY-SQL. There are differences between Entity SQL and T-SQL.

    Further Reading: ADO.NET Entity Framework & Entity SQL

    Entity Framework 6 and Visual Studio 2013

    Entity Framework 6 has been included in Visual Studio 2013. It is also available as a NuGet Package which can be installed by using NuGet Package Manager.

    There are three ways you can work with data models in the Entity Framework: Code First, Model First, and Database First .

    Code First

    Whether you have an existing database or not, you can use the Entity Framework without using the Entity Framework Designer or an .edmx file. If you don’t have a database, you can code your own classes and properties that correspond to tables and columns. If you do have a database, Entity Framework tools can generate the classes and properties that correspond to existing tables and columns. The mapping between the store schema and the conceptual model represented by your code is handled by convention and by a special mapping API. If you let Code First create the database, you can use Code First Migrations to automate the process of deploying the database to production. Migrations can also automate the deployment of database schema changes to production when your data model changes. The following are details:

    Model First

    If you don’t have a database yet, you can begin by creating a model in an .edmx file by using the Entity Framework graphical designer in Visual Studio. When the model is finished, the Entity Framework designer can generate DDL (data definition language) statements to create the database. As in Database First, the .edmx file stores model and mapping information.

    The detail of how to use model first is here.

    Database First

    If you already have a database, the Entity Framework designer built into Visual Studio can automatically generate a data model that consists of classes and properties that correspond to existing database objects such as tables and columns. The information about your database structure (store schema), your data model (conceptual model), and the mapping between them is stored in XML in an .edmx file. The Entity Framework designer provides a graphical UI that you can use to display and edit the .edmx file.

    The detail of how to use database first is here.

    OpenGL Template: summary for 2D/3D shapes and their transformation

    In the last few posts, I documented how I used OpenGL and GLUT on Linux platform to draw very basic 2D and 3D shapes with colours, blended colours, and simple transformations. As a summary, I included a program template developed by jeremiah on Windows Visual Studio. It provides a concise summary of OpenGL basic programming.  I replicated to here to preserve it.

    The program consists of the following four scenes.

    Scene 1: Basic 2D Colour Shapes

    void RenderScene1()
    {
        glMatrixMode( GL_MODELVIEW );                                           // Switch to modelview matrix mode
        glLoadIdentity();                                                       // Load the identity matrix
    
        glTranslatef( -1.5f, 1.0f, -6.0f );                                     // Translate our view matrix back and a bit to the left.
        glColor3f( 1.0f, 0.0f, 0.0f );                                          // Set Color to red
        DrawTriangle( float2(0.0f, 1.0f), float2(-1.0f, -1.0f), float2(1.0f, -1.0f ) );
    
        glTranslatef( 3.0f, 0.0f, 0.0f );                                       // Shift view 3 units to the right
        glColor3f( 0.0f, 0.0f, 1.0f );                                          // Set Color to blue
        DrawRectangle( 2.0f, 2.0f );
    
        glTranslatef( -1.5f, -3.0f, 0.0f );                                     // Back to center and lower screen
        glColor3f( 1.0f, 1.0f, 0.0f );                                          // Set color to yellow
        DrawCircle( 1.0f, 16 );
    }
    

    Here’s the result of scene 1 (by pressing key ‘1’)

    OpenGL template: scene 1 (Basic Shapes)

    OpenGL template: scene 1 (Basic Shapes)

    Scene 2: Basic 2D Shapes with Blended Colours

    void RenderScene2()
    {
        glMatrixMode( GL_MODELVIEW );                                           // Switch to modelview matrix mode
        glLoadIdentity();                                                       // Load the identity matrix
    
        glTranslatef( -1.5f, 1.0f, -6.0f );                                     // Translate back and to the left
        // Draw a triangle with different colors on each vertex
        glBegin( GL_TRIANGLES );
            glColor3f( 1.0f, 0.0f, 0.0f );                                      // Red
            glVertex2f( 0.0f, 1.0f );                                           // Top-Center
    
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex2f( -1.0f, -1.0f );                                         // Bottom-Left
    
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex2f( 1.0f, -1.0f );                                          // Bottom-Right
        glEnd();
    
        glTranslatef( 3.0f, 0.0f, 0.0f );                                       // Translate right
        // Draw a rectangle with different colors on each vertex
        glBegin( GL_QUADS );
            glColor3f( 1.0f, 0.0f, 0.0f );                                      // Red
            glVertex2f( -1.0f, 1.0f );                                          // Top-Left
    
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex2f( 1.0f, 1.0f );                                           // Top-Right
    
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex2f( 1.0f, -1.0f );                                          // Bottom-Right
    
            glColor3f( 1.0f, 1.0f, 1.0f );                                      // White
            glVertex2f( -1.0f, -1.0f );                                         // Bottom-Left
        glEnd();
    
        glTranslatef( -1.5f, -3.0f, 0.0f );                                     // Back to center and lower screen
    
        // Draw a circle with blended red/blue vertices.
        const float step = M_PI / 16;
        const float radius = 1.0f;
    
        glBegin( GL_TRIANGLE_FAN );
            glColor3f( 1.0f, 1.0f, 1.0f );
            glVertex2f(0.0f, 0.0f);
            for ( float angle = 0.0f; angle < ( 2.0f * M_PI ); angle += step )
            {
                float fSin = sinf(angle);
                float fCos = cosf(angle);
    
                glColor3f( ( fCos + 1.0f ) * 0.5f, ( fSin + 1.0f ) * 0.5f , 0.0f);
                glVertex2f( radius * fSin, radius * fCos );
            }
            glColor3f( 1.0f, 0.5f, 0.0f );
            glVertex2f( 0.0f, radius ); // One more vertex to close the circle
        glEnd();
    }
    

    Here’s the result of scene 2 (by pressing key ‘2’)

    OpenGL template: basic shapes wiht blended colour vertices

    OpenGL template: basic shapes wiht blended colour vertices

    Scene 3: Rotating 3-D Shapes

    void RenderScene3()
    {
        glMatrixMode( GL_MODELVIEW );                                           // Switch to modelview matrix mode
        glLoadIdentity();                                                       // Load the identity matrix
    
        glTranslatef( -1.5f, 1.0f, -6.0f );                                     // Translate back and to the left
        glPushMatrix();                                                         // Push the current transformation onto the matrix stack
        glRotatef( g_fRotate1, 0.0f, 0.0f, 1.0f );
        // Draw a triangle with different colors on each vertex
        glBegin( GL_TRIANGLES );
            glColor3f( 1.0f, 0.0f, 0.0f );                                      // Red
            glVertex2f( 0.0f, 1.0f );                                           // Top-Center
    
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex2f( -1.0f, -1.0f );                                         // Bottom-Left
    
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex2f( 1.0f, -1.0f );                                          // Bottom-Right
        glEnd();
        glPopMatrix();
    
        glTranslatef( 3.0f, 0.0f, 0.0f );                                       // Translate right
        glPushMatrix();
        glRotatef( g_fRotate2, 0.0f, 0.0f, 1.0f );
        // Draw a rectangle with different colors on each vertex
        glBegin( GL_QUADS );
            glColor3f( 1.0f, 0.0f, 0.0f );                                      // Red
            glVertex2f( -1.0f, 1.0f );                                          // Top-Left
    
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex2f( 1.0f, 1.0f );                                           // Top-Right
    
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex2f( 1.0f, -1.0f );                                          // Bottom-Right
    
            glColor3f( 1.0f, 1.0f, 1.0f );                                      // White
            glVertex2f( -1.0f, -1.0f );                                         // Bottom-Left
        glEnd();
        glPopMatrix();
    
        glTranslatef( -1.5f, -3.0f, 0.0f );                                     // Back to center and lower screen
        glPushMatrix();
        glRotatef( g_fRotate3, 0.0f, 0.0f, 1.0f );
        // Draw a circle with blended red/blue vertecies
        const float step = M_PI / 16;
        const float radius = 1.0f;
    
        glBegin( GL_TRIANGLE_FAN );
            glColor3f( 1.0f, 1.0f, 1.0f );
            glVertex2f(0.0f, 0.0f);
            for ( float angle = 0.0f; angle < ( 2.0f * M_PI ); angle += step )
            {
                float fSin = sinf(angle);
                float fCos = cosf(angle);
    
                glColor3f( ( fCos + 1.0f ) * 0.5f, ( fSin + 1.0f ) * 0.5f , 0.0f);
                glVertex2f( radius * fSin, radius * fCos );
            }
            glColor3f( 1.0f, 0.5f, 0.0f );
            glVertex2f( 0.0f, radius ); // One more vertex to close the circle
        glEnd();
        glPopMatrix();
    }
    

    Here’s the result of scene 3 (by pressing key ‘3’)

    OpenGL Template: Scene 3 (Rotating 3D Shapes with Blended Colours)

    OpenGL Template: Scene 3 (Rotating 3D Shapes with Blended Colours)

    Scene 4: Rotating 3D Shapes (Pyramid, Cube and Sphere)

    void RenderScene4()
    {
        glMatrixMode( GL_MODELVIEW );
        glLoadIdentity();
    
        glEnable( GL_DEPTH_TEST );
    
        glTranslatef( -1.5f, 1.0f, -6.0f );                                     // Translate back and to the left
    
        glPushMatrix();                                                         // Push the current modelview matrix on the matrix stack
        glRotatef(g_fRotate1, 1.0f, 1.0f, 1.0f );                               // Rotate on all 3 axis
        glBegin( GL_TRIANGLES );                                                // Draw a pyramid
            glColor3f( 1.0f, 0.0f, 0.0f );                                      // Red
            glVertex3f( 0.0f, 1.0f, 0.0f );                                     // Top of front face
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex3f( -1.0f, -1.0f, 1.0f );                                   // Left of front face
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex3f( 1.0f, -1.0f, 1.0f );                                    // Right of front face
    
            glColor3f( 1.0f, 0.0f, 0.0f );                                      // Red
            glVertex3f( 0.0f, 1.0f, 0.0f );                                     // Top of right face
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex3f( 1.0f, -1.0f, 1.0f );                                    // Left of right face
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex3f( 1.0f, -1.0f, -1.0f );                                   // Right of right face
    
            glColor3f( 1.0f, 0.0f, 0.0f );                                      // Red
            glVertex3f( 0.0f, 1.0f, 0.0f );                                     // Top of back face
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex3f( 1.0f, -1.0f, -1.0f );                                   // Left of back face
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex3f( -1.0f, -1.0f, -1.0f );                                  // Right of back face
    
            glColor3f( 1.0f, 0.0f, 0.0f );                                      // Red
            glVertex3f( 0.0f, 1.0f, 0.0f );                                     // Top of left face
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex3f( -1.0f, -1.0f, -1.0f );                                  // Left of left face
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex3f( -1.0f, -1.0f, 1.0f );                                   // Right of left face
        glEnd();
    
        // Render a quad for the bottom of our pyramid
        glBegin( GL_QUADS );
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex3f( -1.0f, -1.0f, 1.0f );                                   // Left/right of front/left face
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex3f( 1.0f, -1.0f, 1.0f );                                    // Right/left of front/right face
            glColor3f( 0.0f, 1.0f, 0.0f );                                      // Green
            glVertex3f( 1.0f, -1.0f, -1.0f );                                   // Right/left of right/back face
            glColor3f( 0.0f, 0.0f, 1.0f );                                      // Blue
            glVertex3f( -1.0f, -1.0f, -1.0f );                                  // Left/right of right/back face
        glEnd();
        glPopMatrix();
    
        glTranslatef( 3.0f, 0.0f, 0.0f );                                        // Translate right
        glPushMatrix();                                                         // Push the current modelview matrix on the matrix stack
        glRotatef( g_fRotate2, 1.0f, 1.0f, 1.0f );                              // Rotate the primitive on all 3 axis
        glBegin( GL_QUADS );
            // Top face
            glColor3f(   0.0f, 1.0f,  0.0f );                                   // Green
            glVertex3f(  1.0f, 1.0f, -1.0f );                                   // Top-right of top face
            glVertex3f( -1.0f, 1.0f, -1.0f );                                   // Top-left of top face
            glVertex3f( -1.0f, 1.0f,  1.0f );                                   // Bottom-left of top face
            glVertex3f(  1.0f, 1.0f,  1.0f );                                   // Bottom-right of top face
    
            // Bottom face
            glColor3f(   1.0f,  0.5f,  0.0f );                                  // Orange
            glVertex3f(  1.0f, -1.0f, -1.0f );                                  // Top-right of bottom face
            glVertex3f( -1.0f, -1.0f, -1.0f );                                  // Top-left of bottom face
            glVertex3f( -1.0f, -1.0f,  1.0f );                                  // Bottom-left of bottom face
            glVertex3f(  1.0f, -1.0f,  1.0f );                                  // Bottom-right of bottom face
    
            // Front face
            glColor3f(   1.0f,  0.0f, 0.0f );                                  // Red
            glVertex3f(  1.0f,  1.0f, 1.0f );                                  // Top-Right of front face
            glVertex3f( -1.0f,  1.0f, 1.0f );                                  // Top-left of front face
            glVertex3f( -1.0f, -1.0f, 1.0f );                                  // Bottom-left of front face
            glVertex3f(  1.0f, -1.0f, 1.0f );                                  // Bottom-right of front face
    
            // Back face
            glColor3f(   1.0f,  1.0f,  0.0f );                                 // Yellow
            glVertex3f(  1.0f, -1.0f, -1.0f );                                 // Bottom-Left of back face
            glVertex3f( -1.0f, -1.0f, -1.0f );                                 // Bottom-Right of back face
            glVertex3f( -1.0f,  1.0f, -1.0f );                                 // Top-Right of back face
            glVertex3f(  1.0f,  1.0f, -1.0f );                                 // Top-Left of back face
    
            // Left face
            glColor3f(   0.0f,  0.0f,  1.0f);                                   // Blue
            glVertex3f( -1.0f,  1.0f,  1.0f);                                   // Top-Right of left face
            glVertex3f( -1.0f,  1.0f, -1.0f);                                   // Top-Left of left face
            glVertex3f( -1.0f, -1.0f, -1.0f);                                   // Bottom-Left of left face
            glVertex3f( -1.0f, -1.0f,  1.0f);                                   // Bottom-Right of left face
    
            // Right face
            glColor3f(   1.0f,  0.0f,  1.0f);                                   // Violet
            glVertex3f(  1.0f,  1.0f,  1.0f);                                   // Top-Right of left face
            glVertex3f(  1.0f,  1.0f, -1.0f);                                   // Top-Left of left face
            glVertex3f(  1.0f, -1.0f, -1.0f);                                   // Bottom-Left of left face
            glVertex3f(  1.0f, -1.0f,  1.0f);                                   // Bottom-Right of left face
        glEnd();
        glPopMatrix();
    
        glTranslatef( -1.5f, -3.0f, 0.0f );                                     // Back to center and lower screen
        glPushMatrix();
        glRotatef( g_fRotate3, 1.0f, 1.0f, 1.0f );
        glColor3f( 1.0f, 1.0f, 0.0f );                                          // Yellow
        glutSolidSphere( 1.0f, 16, 16 );                                        // Use GLUT to draw a solid sphere
        glScalef( 1.01f, 1.01f, 1.01f );
        glColor3f( 1.0f, 0.0f, 0.0f );                                          // Red
        glutWireSphere( 1.0f, 16, 16 );                                         // Use GLUT to draw a wireframe sphere
        glPopMatrix();
    }
    

    Here’s the result of scene 4 (by pressing key ‘4’)

    OpenGL Template: rotating 3D pyramid, cubes and wireframe sphere

    OpenGL Template: rotating 3D pyramid, cube and wireframed sphere

    OpenGL 3D Cuboid Transformation Example

    The following example demonstrates how to draw a cuboid, add lighting and transforming to illustrates the 3D capability in OpenGL. In order to show the lighting effects, I purposely don’t draw the top and bottom of cuboid. It’s fun to change the colour, lighting, and transformation (rotating).

    /*
    /*
    * Transform3DCuboid.cpp
    *
    * 	This program shows a 3-D cuboid in rotation.
    *
    * To compile:
    *	gcc Transform3DCuboid.cpp -lglut -lGL -lGLU
    */
    #include <iostream>
    #include <stdlib.h>
    #include <GL/glut.h>
    
    using namespace std;
    
    //Called when a key is pressed
    void handleKeypress(unsigned char key, int x, int y) {
    	switch (key) {
    		case 27: //Escape key
    			exit(0);
    	}
    }
    
    //Initializes 3D rendering
    void initRendering() {
    	glEnable(GL_DEPTH_TEST);
    	glEnable(GL_COLOR_MATERIAL);
    	glEnable(GL_LIGHTING); //Enable lighting
    	glEnable(GL_LIGHT0); //Enable light #0
    	glEnable(GL_LIGHT1); //Enable light #1
    	glEnable(GL_NORMALIZE); //Automatically normalize normals
    	//glShadeModel(GL_SMOOTH); //Enable smooth shading
    }
    
    //Called when the window is resized
    void handleResize(int w, int h) {
    	glViewport(0, 0, w, h);
    	glMatrixMode(GL_PROJECTION);
    	glLoadIdentity();
    	gluPerspective(45.0, (double)w / (double)h, 1.0, 200.0);
    }
    
    float _angle = -70.0f;
    
    //Draws the 3D scene
    void drawScene() {
    	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    	glMatrixMode(GL_MODELVIEW);
    	glLoadIdentity();
    
    	glTranslatef(0.0f, 0.0f, -8.0f);
    
    	//Add ambient light
    	GLfloat ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f}; //Color (0.2, 0.2, 0.2)
    	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);
    
    	//Add positioned light
    	GLfloat lightColor0[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Color (0.5, 0.5, 0.5)
    	GLfloat lightPos0[] = {4.0f, 0.0f, 8.0f, 1.0f}; //Positioned at (4, 0, 8)
    	glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
    	glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
    
    	//Add directed light
    	GLfloat lightColor1[] = {0.5f, 0.2f, 0.2f, 1.0f}; //Color (0.5, 0.2, 0.2)
    	//Coming from the direction (-1, 0.5, 0.5)
    	GLfloat lightPos1[] = {-1.0f, 0.5f, 0.5f, 0.0f};
    	glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
    	glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);
    
    	glRotatef(_angle, 0.0f, 1.0f, 1.0f);
    	//Set the colour here
    	glColor3f(1.0f, 0.0f, 0.0f);
    	glBegin(GL_QUADS);
    
    	//Front
    	glNormal3f(0.0f, 0.0f, 1.0f);
    	//glNormal3f(-1.0f, 0.0f, 1.0f);
    	glVertex3f(-1.5f, -1.0f, 1.5f);
    	//glNormal3f(1.0f, 0.0f, 1.0f);
    	glVertex3f(1.5f, -1.0f, 1.5f);
    	//glNormal3f(1.0f, 0.0f, 1.0f);
    	glVertex3f(1.5f, 1.0f, 1.5f);
    	//glNormal3f(-1.0f, 0.0f, 1.0f);
    	glVertex3f(-1.5f, 1.0f, 1.5f);
    
    	//Right
    	glNormal3f(1.0f, 0.0f, 0.0f);
    	//glNormal3f(1.0f, 0.0f, -1.0f);
    	glVertex3f(1.5f, -1.0f, -1.5f);
    	//glNormal3f(1.0f, 0.0f, -1.0f);
    	glVertex3f(1.5f, 1.0f, -1.5f);
    	//glNormal3f(1.0f, 0.0f, 1.0f);
    	glVertex3f(1.5f, 1.0f, 1.5f);
    	//glNormal3f(1.0f, 0.0f, 1.0f);
    	glVertex3f(1.5f, -1.0f, 1.5f);
    
    	//Back
    	glNormal3f(0.0f, 0.0f, -1.0f);
    	//glNormal3f(-1.0f, 0.0f, -1.0f);
    	glVertex3f(-1.5f, -1.0f, -1.5f);
    	//glNormal3f(-1.0f, 0.0f, -1.0f);
    	glVertex3f(-1.5f, 1.0f, -1.5f);
    	//glNormal3f(1.0f, 0.0f, -1.0f);
    	glVertex3f(1.5f, 1.0f, -1.5f);
    	//glNormal3f(1.0f, 0.0f, -1.0f);
    	glVertex3f(1.5f, -1.0f, -1.5f);
    
    	//Left
    	glNormal3f(-1.0f, 0.0f, 0.0f);
    	//glNormal3f(-1.0f, 0.0f, -1.0f);
    	glVertex3f(-1.5f, -1.0f, -1.5f);
    	//glNormal3f(-1.0f, 0.0f, 1.0f);
    	glVertex3f(-1.5f, -1.0f, 1.5f);
    	//glNormal3f(-1.0f, 0.0f, 1.0f);
    	glVertex3f(-1.5f, 1.0f, 1.5f);
    	//glNormal3f(-1.0f, 0.0f, -1.0f);
    	glVertex3f(-1.5f, 1.0f, -1.5f);
    
    	glEnd();
    
    	glutSwapBuffers();
    }
    
    void update(int value) {
    	_angle += 1.5f;
    	if (_angle > 360) {
    		_angle -= 360;
    	}
    
    	glutPostRedisplay();
    	glutTimerFunc(25, update, 0);
    }
    
    int main(int argc, char** argv) {
    	//Initialize GLUT
    	glutInit(&argc, argv);
    	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    	glutInitWindowSize(400, 400);
    
    	//Create the window
    	glutCreateWindow("Rotating 3D Cuboid");
    	initRendering();
    
    	//Set handler functions
    	glutDisplayFunc(drawScene);
    	glutKeyboardFunc(handleKeypress);
    	glutReshapeFunc(handleResize);
    
    	//Add a timer
    	glutTimerFunc(25, update, 0);
    
    	glutMainLoop();
    }
    
    Rotating a 3D Cuboid in OpenGL

    Rotating a 3D Cuboid in OpenGL