Monday, October 15, 2012

Install and configure Sonar on Windows 7 for .NET projects

It has been a very long time since I post anything. I apologize for this. I will definitely try to do this more often.
Recently, I have been managing and analyzing code quality metrics using Sonar with C# plugins for .NET projects Sonar, as described on their website, is a quality management platform, dedicated to continuously analyze and measure technical quality from project portfolio to method.  It is extensible and configurable for multiple programming languages.  It provides a report friendly accessible web user interface to manage project analysis results that contain detailed information for code coverage, complexity, coupling, duplication, rules violations for coding standards, etc.  It is definitely a good option to consider for code analysis management.
Even though it’s very easy to follow the steps explained on their site, I have prepared this detailed post on how to install and configure Sonar on Windows 7 OS.  there are a few things to consider for minimizing the effort and prevent troubleshooting too much while installing and configuring Sonar. The main purpose of this post is to get hands on experience with Sonar and have it running in 10 minutes… of course after the pre-requisites are installedJ.
Let’s get down to business with my sample solution named JobSeekerWeb:

1. Software used
2. Considerations
  • Run command prompt (cmd) as Administrator.
  • Sonar uses port 9000 by default; it could be configure to use other available port.  In my example, I configured port 9090 (shown after). Check port availability by running netstat –a in a command prompt.
  • If you’re running 32 bit version of Java JDK, you must also run 32 bit version of Sonar as well (shown after).  Check your current Java JDK version by running java –version in a command prompt.
3. Installation
  1. Make sure to have Java JDK installed. Its default path for 32 bit version is C:\Program Files (x86)\Java\jdk1.6.0_29
  2. Unzip sonar-3.2.zip file. I used this path C:\Sonar
  3. Unzip sonar-runner-2.0.zip file. I used the Sonar's folder C:\Sonar\Sonar-runner-2.0
  4. Unzip the CSharpPluginsEcosystem-1.4.zip file into your Sonar’s plugins folder C:\Sonar\extensions\plugins
  5. Install FxCop 1.36. Its default installation folder is C:\Program Files (x86)\Microsoft FxCop 1.36
  6. Install Gallio. Its default installation folder is C:\Program Files\Gallio
  7. Install OpenCover to gather coverage statistics for your app. Its default installation folder is C:\Program Files (x86)\OpenCover
4. Configuration

Note: .properties files can be edited by any text editor like Notepad or Notepad++. I prefer to use Notepad++, it helps to read these files better.
  1. Edit Sonar configuration file (sonar.properties).  Path C:\Sonar\conf
    Remove
    the # sign of the following line and assign port number. I used port 9090 (view image).

  2. Edit sonar-runner configuration file (sonar-runner.properties).  Path C:\Sonar\sonar-runner-2.0\conf
    Remove
    the # sign of the following two lines and assign host and port configured in sonar.properties.  The same for the encoding at the end (view image).
  3. Add or Edit two new environment variables %JAVA_HOME% and %SONAR_RUNNER_HOME%.  Also Edit %PATH% variable to add Sonar-Runner path (view image).

    To open the environment variables dialog box:
    Right click > Computer > click Properties > click Advanced system settings > tap Advance > click button Environment Variables

    Note
    : Notice that I’m using the same paths previously highlighted above.
  4. Create a file: sonar-project.properties and configure it (view image).  Save this file in the same folder of your solution (.sln file).  The path for my sample solution is C:\Workspaces\JobSeekerWeb





    Text of above screen shot:

    # Project identification 
    sonar.projectKey=JS:JobSeekerWeb
    sonar.projectVersion=1.0
    sonar.projectName=Job Seeker Web
      
    # Info required for Sonar 
    sonar.sources=. 
    sonar.language=cs 
      
    #Core C# Settings 
    sonar.dotnet.visualstudio.solution.file=JobSeekerWeb.sln 
    sonar.dotnet.4.0.sdk.directory=C:/WIndows/Microsoft.NET/Framework/v4.0.30319
    sonar.dotnet.version=4.0
    sonar.donet.visualstudio.testProjectPattern=*UnitTests*;*test*;*Test*
    sonar.fxcop.installDirectory=C:/Program Files (x86)/Microsoft FxCop 1.36
    sonar.gallio.installDirectory=C:/Program Files/Gallio
    sonar.opencover.installDirectory=C:/Program Files (x86)/OpenCover
    sonar.gallio.coverage.tool=OpenCover
    sonar.gallio.runner=IsolatedProcess
    sonar.gallio.timeoutMinutes=60
    sonar.fxcop.assemblyDependencyDirectories=c:/Program Files (x86)/Microsoft ASP.NET/ASP.NET MVC 3/Assemblies,C:/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/IDE/PublicAssemblies,c:/Program Files (x86)/Microsoft ASP.NET/ASP.NET Web Pages/v1.0/Assemblies

    # Exclusions Settings
    sonar.skippedModules=UnitTests


    Note: Notice that I’m using the same paths previously highlighted above.
5. Running Sonar and Getting Analysis Reports
  1. Find 32 bit version of Sonar.  Path C:\Sonar\bin\windows-x86-32and start Sonar Service by opening a command prompt and running StartSonar (view image).  You should get an output like the image below.

    Note
    : It could also be install as a service by running InstallNTService and then StartNTService.  If it doesn’t work just configure the service manually by changing the default user to Network Service.
  2. My Sonar's page is http://localhost:9090 as configured previously in the sonar.properties file.
  3. Execute Sonar-Runner against the sample solution.  Start up command prompt from where the solution (.sln) and sonar-project.properties files are located and start sonar-runner (view image).  After it finishes refresh the Sonar 's page (previous step).  You should see the project analysis result listed.



    Note
    : It could take a couple of minutes. All depends on the size of the solution, number of projects, tests to run, etc.
  4. View dashboard with Sonar Code Analysis project output.  Click on project name “Job Seeker Web” which was previously assigned in the sonar-project.properties file on line sonar.projectName=Job Seeker Web
  5. Login to Sonar by clicking Log in link on the top right of the page. The default user and password is admin as left in the sonar.properties file.  Once loged in you have other options to configured and extend.
6. Summary
We have successfully installed and configured Sonar and Sonar-Runner on Windows 7 OS for C# solution with its default configuration and embedded database.  
 
Here are some features I would recommend you try:
1.   Configure another database, such as Oracle, SQL Server, MySQL, etc. to store analysis output.
2.   Access Sonar service remotely other than localhost.  The sonar-runner needs to be local, but not the service. 
3.   Modify rules template for FxCop.
4.   Configure Gallio differently than default.
5.   Switch coverage engine, try NCover for example.
6.   Activate Sonar’s support for integration tests feature.
7.   Configure Sonar to be part of your deployment.
If you want more information and details about Sonar follow the link: http://docs.codehaus.org/display/SONAR/Documentation.
Thanks for reading, I really hope you find this helpful.

Tuesday, June 15, 2010

Entity Framework 4.0 and T4 templates to generate POCO classes


Hi guys, thanks for visiting again.  This post is to have a brief introduction on how to work with T4 templates that generates ObjectContext and POCO classes dynamically.  In this example, we're going customize the context template with a free template editor which is going to make our life easier with it's features.  After we're going to run the test performance.
We are going to proceed as follows:
  • Download ADO.NET C# T4 Entity Code Generator, is an existing T4 template that can be used to generate persistence ignorant entity types (POCO classes) from an Entity Data Model.
  • Install the Tangible T4 Editor for Visual Studio 2010, which is an editor basically adds IntelliSense and Syntax Coloring to T4 Text Templates.
  • Test how this T4 template generates our Context and POCO classes.
  • Run the performance test.
Let's add a class libray project named EF4ApplicationWithPOCOTemplate, just to keep the name convention from my previous post
Let's create our model (edmx file) as we did in the previous post on POCO performance.

In order to have the template available, we need to install the ADO.NET C# POCO Entity Generator.   
After installation is finished, you might need to restart Visual Studio to see the new template available.  Add it to your project from the Add new item menu.
When adding the template you'll be prompt a Security Warning window to confirm the execution of the template.  In this window we choose OK, no because we ignore the message, but because we know it will generate our POCO Classes :-), besides it's going to run every time we save it.
After adding the templates, we'll have an awfull error message related to System.IO.FileNotFoundException
Basically this error message is because it cannot find the Entity Data Model file (edmx file) which provides the source metadata that is used to generate the code for both the POCO classes and the ObjectContextTo fix this issue, we just need to open both files and replace the @"$edmxInputFile$" with the name of our edmx file.
After modifying and saving both template files (.tt) with the correct edmx filename, they will generate the POCO and ObjectContext classes as expected and add them to the project.
Now, we have our project with auto generated POCO and ObjectContext classes that works fine; however, since we want to modify and customize the templates as needed, let's start comparing both versions we have in the solution.  

One is the manually created ObjectContext from the previous post and the new one generated by the T4 template.
As shown, there are a couple of differences between these two classes. 
Let's open the context EF4ApplicationWithPOCOTemplate.Context.tt file.
The first thing I thought when looking at the content of the file is "NOTEPAD".  So, I decided to search for a friendly interface that helps me modify this file.  You'll notice that there are many T4 template editors out there.  For this example, we're going to use a FREE tool named Tangible T4 Template Editor.  It will change the whole appearance of the file content by adding features such as intellisense and syntax coloring.

I will only select to Install T4 Editor this time.  If you want, you can install the Modeling tools as well. 
After installing this tool and restarting Visual Studio, you can manage the installation with the Extension Manager, which is in the Tools menu.
Now we're ready to open the template file and change it using the features added.
For this example, I have changed the template so it generates the exact same code, for the ObjectContext, as the manually POCO generated class from the previous post.
File modified content: EF4ApplicationWithPOCOTemplate.Context.tt (all content)
<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#><#@
 output extension=".cs"#><#

CodeGenerationTools code = new CodeGenerationTools(this);
MetadataTools ef = new MetadataTools(this);
MetadataLoader loader = new MetadataLoader(this);

string inputFile = @"EF4DomainModelForPOCOTemplate.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = code.VsNamespaceSuggestion();

EntityContainer container = ItemCollection.GetItems<EntityContainer>().FirstOrDefault();
if (container == null)
{
    return "// No EntityContainer exists in the model, so no code was generated";
}
#>
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from MY ADJUSTED TEMPLATE!!!!!!!.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Data.Objects;
using System.Data.EntityClient;

<#
if (!String.IsNullOrEmpty(namespaceName))
{
#>
namespace <#=code.EscapeNamespace(namespaceName)#>
{
<#
    PushIndent(CodeRegion.GetIndent(1));
}
#>
<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : ObjectContext
{
    public <#=code.Escape(container)#>() : base("name=<#=container.Name#>", "<#=container.Name#>")
    {
<#
        WriteLazyLoadingEnabled(container);
#>
    }
<#
        foreach (EntitySet entitySet in container.BaseEntitySets.OfType<EntitySet>())
        {
#>

    private ObjectSet<<#=code.Escape(entitySet.ElementType)#>> <#=code.FieldName(entitySet)#>;
    <#=Accessibility.ForReadOnlyProperty(entitySet)#> ObjectSet<<#=code.Escape(entitySet.ElementType)#>> <#=code.Escape(entitySet)#>
    {
        get { 
                if(<#=code.FieldName(entitySet) #>==null) 
                    <#=code.FieldName(entitySet)#> = CreateObjectSet<<#=code.Escape(entitySet.ElementType)#>>("<#=entitySet.Name#>"); 
                return <#=code.FieldName(entitySet) #>;
            }
    }
    
    public void AddTo<#=code.Escape(entitySet)#>(<#=code.Escape(entitySet.ElementType)#> <#=code.Escape(entitySet).ToLower().Trim('s') #>){
        <#=entitySet.Name#>.AddObject(<#=code.Escape(entitySet).ToLower().Trim('s') #>);
    }
<#
        }
#>
}
<#
if (!String.IsNullOrEmpty(namespaceName))
{
    PopIndent();
#>
}
<#
}
#>
<#+
private void WriteLazyLoadingEnabled(EntityContainer container)
{
   string lazyLoadingAttributeValue = null;
   string lazyLoadingAttributeName = MetadataConstants.EDM_ANNOTATION_09_02 + ":LazyLoadingEnabled";
   if(MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, out lazyLoadingAttributeValue))
   {
       bool isLazyLoading = false;
       if(bool.TryParse(lazyLoadingAttributeValue, out isLazyLoading))
       {
#>
        this.ContextOptions.LazyLoadingEnabled = <#=isLazyLoading.ToString().ToLowerInvariant()#>;
<#+
       }
   }
}
#>

To test the generated results, I've just copied and pasted the folder that contains the class with CRUD operations from previous post, then renamed the file and class.  After just add a couple of lines in the console application to run it.
After running the application I have the following results.
Conclusions
  • The C# T4 Entity Code Generator for POCO works great and the best thing is that it can be customized as needed. 
  • The Tangible T4 Editor is a good tool to modify these files.
  • The performance was increased.
What's next?
I'm thinking on writing about extending performance test for EF 4.0, refactoring current solution, repository pattern implementation, MVC 2 pattern, WCF Data Services, etc.  I'm always open to suggestions.    

Monday, May 17, 2010

Entity Framework 4.0 and POCO Performance

In this post we're going to run the same tests we ran in our previous post; however, these tests will be done with POCO (Plain Old CLR Object) classes in place.

We're going to perform the following:
  • Rearrange solution project and files.
  • Create POCO Classes.
  • Create ObjectContext.
  • Run CRUD operations and Performance test.
  • Compare results of auto generated Entities against POCO classes.

Let's start by changing the file arrangements in our solution.  Let's add two class library projects: one to keep the database scripts and batch file and another named EFApplicationWithPOCO for the POCO Classes and Context.  



Add a new ADO.NET Entity Data Model by using the Update Model From Database wizard to generate the model. 


Empty the Custom Tool property of the Edmx file.  This will remove the EF4DomainModelForPOCO.Designer.cs auto generated file and it won't generated again.


Write your POCO and ObjectContext classes.

Role.cs
using System;
using System.Collections.Generic;

namespace EF4ApplicationWithPOCO
{
    public class Role
    {
        public Int32 RoleId { get; set; }
        public String RoleName { get; set; }
        public virtual List<User> Users { get; set; }
    }
}
User.cs
using System;
namespace EF4ApplicationWithPOCO
{
    public class User
    {
        public Int32 UserId { get; set; }
        public String UserName { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public Int32 RoleId { get; set; }
        public virtual Role Role { get; set; }
    }
}
EF4ApplicationPOCOContext.cs
using System.Data.Objects;

namespace EF4ApplicationWithPOCO
{
    public class EF4ApplicationPOCOContext : ObjectContext
    {
        public EF4ApplicationPOCOContext() : base("name=EF4DomainModelContainerForPOCO", "EF4DomainModelContainerForPOCO")
        {
            ContextOptions.LazyLoadingEnabled = true;
        }

        private ObjectSet<User> _users;
        public ObjectSet<User> Users
        {
            get
            {
                if (_users == null)
                    _users = CreateObjectSet<User>("Users");
                return _users;
            }
        }

        private ObjectSet<Role> _roles;
        public ObjectSet<Role> Roles
        {
            get
            {
                if (_roles == null)
                    _roles = CreateObjectSet<Role>("Roles");
                return _roles;
            }
        }

        public void AddToRoles(Role role)
        {
            Roles.AddObject(role);
        }

        public void AddToUsers(User user)
        {
            Users.AddObject(user);
        }
    }
}
Now that we've created our POCO and ObjectContext classes, we can add code to the TestCrudeOperationsWithPOCO.cs class and implement it as follows.
using System;
using System.Linq;
using EF4ApplicationInterfaces;

namespace EF4ApplicationWithPOCO.Temp
{
    public class TestCrudeOperationsWithPOCO : IEF4ApplicationTest
    {
        public void CreateDbTest()
        {
            using (var context = new EF4ApplicationPOCOContext())
            {
                Console.WriteLine("INSERTING ROLES TO DATABASE");
                context.AddToRoles(new Role {RoleName = "Role 1"});
                context.AddToRoles(new Role {RoleName = "Role 2"});
                context.AddToRoles(new Role {RoleName = "Role 3"});
                context.SaveChanges();

                Console.WriteLine("INSERTING USERS TO DATABASE");
                var firstRole = context.Roles.Where(t => t.RoleName == "Role 1").FirstOrDefault();
                context.AddToUsers(
                    new User
                    {
                        UserName = "user1",
                        FirstName = "FirstName1",
                        LastName = "LastName1",
                        DateOfBirth = new DateTime(1980, 12, 10),
                        Role = firstRole
                    });
                var secondRole = context.Roles.Where(t => t.RoleName == "Role 2").FirstOrDefault();
                context.AddToUsers(
                    new User
                    {
                        UserName = "user2",
                        FirstName = "FirstName2",
                        LastName = "LastName2",
                        DateOfBirth = new DateTime(1980, 12, 11),
                        Role = secondRole
                    });
                var thridRole = context.Roles.Where(t => t.RoleName == "Role 3").FirstOrDefault();
                context.AddToUsers(
                    new User
                    {
                        UserName = "user3",
                        FirstName = "FirstName3",
                        LastName = "LastName3",
                        DateOfBirth = null,
                        Role = thridRole
                    });
                context.SaveChanges();
            }
        }

        public void UpdateDbTest()
        {
            using (var context = new EF4ApplicationPOCOContext())
            {
                Console.WriteLine("UPDATING USER INFORMATION");
                var user1 = context.Users.Where(t => t.UserName == "user1").FirstOrDefault();
                user1.FirstName = "Alexandro";
                user1.LastName = "Velarde";
                context.SaveChanges();
            }
        }

        public void ReadFromDbTest()
        {
            using (var context = new EF4ApplicationPOCOContext())
            {
                Console.WriteLine("VIEW INSERTED USERS");
                var users = context.Users;
                foreach (var u in users)
                {
                    Console.WriteLine(string.Format(
                        "UserName = {0}, FirstName = {1}, LastName = {2}, DateOfBirth = {3}",
                        u.UserName, u.FirstName, u.LastName,
                        u.DateOfBirth.HasValue ? u.DateOfBirth.Value.ToString("MM/dd/yyyy")
                        : string.Empty));
                }
            }
        }

        public void PerformanceTest()
        {
            using (var context = new EF4ApplicationPOCOContext())
            {
                var users = context.Users;
                Console.WriteLine("PERFORMANCE TEST STARTED...");
                var user = users.FirstOrDefault();
                string readValueOneMillionTimes = null;
                var timeWhenTestStarted = DateTime.Now;
                for (int i = 0; i < 1000000; i++)
                    readValueOneMillionTimes = user.Role.RoleName;

                var duration = DateTime.Now.Subtract(timeWhenTestStarted);
                Console.WriteLine("VALUE READ: " + readValueOneMillionTimes +
                                  " DURATION: " + duration.TotalMilliseconds + " MILLISECONDS");
                Console.WriteLine("PERFORMANCE TEST END");
            }
        }

        public void DeleteFromDbTest()
        {
            using (var context = new EF4ApplicationPOCOContext())
            {
                Console.WriteLine("DELETE USERS FROM DATABASE");
                foreach (var userToDelete in context.Users)
                    context.DeleteObject(userToDelete);

                foreach (var role in context.Roles)
                    context.DeleteObject(role);
                context.SaveChanges();
            }
        }

        public void RunAllTest()
        {
            CreateDbTest();
            Console.WriteLine();

            UpdateDbTest();
            Console.WriteLine();

            ReadFromDbTest();
            Console.WriteLine();

            PerformanceTest();
            Console.WriteLine();

            DeleteFromDbTest();
            Console.ReadKey();
        }
    }
}

Now let's RUN our the performance test for both projects and COMPARE the results.

Program.cs
using System;
using EF4Application.Temp;
using EF4ApplicationWithPOCO.Temp;

namespace EF4ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("====== RUNNING AUTO GENERATED CLASSES ======");
            new TestCrudeOperationsNoPOCO().RunAllTest();
            
            Console.WriteLine("====== RUNNING POCO CLASSES TEST =======");
            new TestCrudeOperationsWithPOCO().RunAllTest();
        }
    }
}

Here are the results.  Look at the huge difference between POCO and auto generated entities.
Summary
I think there should be more performance test to be done, but thisone gives you a good idea on where to focus. 

What's next?
In the next post, I can enhance the performance test with much more complex cases to measure the POCO performance for tracking.  After we can see how to write templates to auto generate POCO classes or any good idea you can come up with...  Let me know!.

I hope this was useful, thanks for reading..

Monday, May 10, 2010

Entity Framework 4.0 Walk-through

This example is a walk-through the basic characteristics of Entity Framework 4.0.  In this example we'll see how to perform the following:
  • Create an Entity Framework 4.0 based application with Visual Studio 2010.
  • Model First Development by creating your Entity Model first and then generate DDL to create the database with maching tables and relations.
  • Create relations (associations) between entities.
  • Create a Mount database batch file that will run our script to create our database and its objects.
  • Execute CRUD operations (Create, Read, Update, Delete) over our database.
Let's start by creating a new Class Library project and add an ADO.NET Entity Data Model.

When the Entity Data Model Wizard dialog appears, choose an Empty Model content.

Add the two Entities (Role and User) that will represent our database tables for this example.  If the database had already existed, we can choose Update Model from Database and select the objects from our database such as tables, stores procedures and functions.

Add the Properties needed to define each Entity. In the properties window we can define type, size and nullability for each property.
Create Association between the entities Role and User.  Right click on the Entity Role and select Add -> Association.
After the Association is added, it can be configured in the properties window or open the Referential Constraint window by double clicking on it.
To view the definition of the table that will be created in the database, we can select the Entity, right click on it and select Table Mapping.
The create database DDL can be generated from the Model by right clicking on it and selecting Generate Database from Model.  If the database existed just click on Update Model from Database and select database objects.
When Generate Database Wizard dialog appears, specify a name for the new ConnectionString that will be added to a configuration file in the application.
After clicking the Next button in the Generate Database Wizard it will generate the SQL script to create database objects from the Model.
Create a batch file and added as an external tool in the Visual Studio.  It will run the Create Database script (manually added) and the one generated by Entity Framework.  This can be easily run each time the Model or Database is modified.
After building the application and clicking the button to show all files, there are three files generated.  The Conceptual schema definition language (CSDL), store schema definition language (SSDL), and mapping specification language (MSL) which are XML-based languages that respectively describe the conceptual model, storage model, and the mapping between these models. These files are generated at build time and the EF needs them at run time.
The EF4DomainModel.Designer.cs was created with the EDMX file.  This file contains the Context, Entities and Types generated by the code generator defined by default in the Custom Tool property of the EDMX file.
Now let’s write some code to test the application with CRUD operations.
  • Add a Console Application to the solution.
  • Copy the App.config and pasted to the Console Application.
  • Create a folder name Temp and Add a TestCrudeOperations.cs class.

In the class TestCrudeOperations.cs add the code bellow. This is what we're doing:
  • Insert all the Roles and Users to the database.
  • Update User information.
  • Read and List the three inserted Users.
  • Read a property a Million times to measure performance in milliseconds.
  • Delete all the Roles and Users from the database.
We have to call the method SaveChanges() from our context to commit our changes to our database.
using System;
using System.Linq;
namespace EF4Application.Temp
{
    public class TestCrudeOperations
    {
        public void RuntTest()
        {
            using (var context = new EF4DomainModelContainer())
            {
                Console.WriteLine("INSERTING ROLES TO DATABASE");
                context.AddToRoles(new Role { RoleName = "Role 1" });
                context.AddToRoles(new Role { RoleName = "Role 2" });
                context.AddToRoles(new Role { RoleName = "Role 3" });
                context.SaveChanges();

                Console.WriteLine("INSERTING USERS TO DATABASE");
                var firstRole = context.Roles.Where(t =>t.RoleName=="Role 1").FirstOrDefault();
                context.AddToUsers(
                    new User
                    {
                        UserName = "user1",
                        FirstName = "FirstName1",
                        LastName = "LastName1",
                        DateOfBirth = new DateTime(1980, 12, 10),
                        Role = firstRole
                    });
                var secondRole = context.Roles.Where(t =>t.RoleName=="Role 2").FirstOrDefault();
                context.AddToUsers(
                    new User
                        {
                            UserName = "user2", 
                            FirstName = "FirstName2", 
                            LastName = "LastName2", 
                            DateOfBirth = new DateTime(1980, 12, 11), 
                            Role = secondRole
                        });
                var thridRole = context.Roles.Where(t =>t.RoleName=="Role 3").FirstOrDefault();
                context.AddToUsers(
                    new User
                        {
                            UserName = "user3", 
                            FirstName = "FirstName3", 
                            LastName = "LastName3", 
                            DateOfBirth = null, 
                            Role = thridRole
                        });
                context.SaveChanges();

                Console.WriteLine("UPDATING USER INFORMATION");
                var user1 = context.Users.Where(t => t.UserName == "user1").FirstOrDefault();
                user1.FirstName = "Alexandro";
                user1.LastName = "Velarde";
                context.SaveChanges();

                Console.WriteLine("VIEW INSERTED USERS");
                var users = context.Users;
                foreach (var u in users)
                {
                    Console.WriteLine(string.Format(
                        "UserName = {0}, FirstName = {1}, LastName = {2}, DateOfBirth = {3}",
                        u.UserName, u.FirstName, u.LastName, 
                        u.DateOfBirth.HasValue ? u.DateOfBirth.Value.ToString("MM/dd/yyyy") 
                        : string.Empty));
                }

                Console.WriteLine("PERFORMANCE TEST STARTED...");
                var user = users.FirstOrDefault();
                string readValueOneMillionTimes = null;
                var timeWhenTestStarted = DateTime.Now;
                for (int i = 0; i < 1000000; i++)
                {
                    readValueOneMillionTimes = user.Role.RoleName;
                }
                var duration = DateTime.Now.Subtract(timeWhenTestStarted);
                Console.WriteLine("VALUE READ: " + readValueOneMillionTimes + 
                                  " DURATION: " + duration.TotalMilliseconds + " MILLISECONDS");
                Console.WriteLine("PERFORMANCE TEST END");

                Console.WriteLine("DELETE USERS FROM DATABASE");
                foreach (var userToDelete in context.Users)
                    context.DeleteObject(userToDelete);

                foreach (var role in context.Roles)
                    context.DeleteObject(role);
                context.SaveChanges();
                Console.ReadKey();
            }
        }
    }
}
In the Console Application, let’s write the following code in the Main method.
This are the test results in the Console Application.
From the SQL Management Studio, if we do a select to both tables Roles and Users, we’ll see the following results.

Conclusion
With this post we were able to execute and persist data in our database.  The performance test is intented to be compared after, when we see POCO classes.

What's next?
As always, I'm opened to suggestions...for now, this is what I have in mind for next posts: POCO classes and templates for code generation, Change Tracking with POCO (Snapshot and Notification based), Implementing Repository and Unit of Work pattern with Entity Framework 4.0., etc..