Entity Framework and Plain Old CLR Objects in an ASP.Net application

This is going to be the sixth post of a series of posts regarding ASP.Net and the Entity Framework and how we can use Entity Framework to access our datastore. You can find the first one here, the second one here and the third one here , the fourth one here and the fifth one here.

I have a post regarding ASP.Net and EntityDataSource. You can read it here.I have 3 more posts on Profiling Entity Framework applications. You can have a look at them here, here and here.

In this post I will be looking into the issue of Pocos and how to leverage their use in Entity framework in an ASP.Net application.

I assume that you have access to a version of SQL Server.If you do not, you can download and install the free SQL Server Express edition from here. 

In this post (step 9) you will find a T-SQL script that will create the database objects of the CompanyEmployees database.Before that you execute the T-SQL script you must create in the Query window the CompanyEmployees database yourself. You can download the companiesemployeesinsertt.zip to insert data into the tables.

1) Launch Visual Studio 2010 (express edition will work fine). Create an empty ASP.Net web site from the available templates and choose a suitable name for it. Choose C# as the development language.

2) Add a new project to your solution, a class library project.Remove the class1.cs file from the project.

3) Add a new ADO.Net Entity Data model to the class library project. Choose a suitable name for it, e.g CompanyEmployees.edmx.

4) Then the Wizard pops up. Choose "Generate from Database" option and finish the steps of the wizard by selecting only the tables to be included in the model.If you have done everything correctly so far you will have the model as it is displayed in the picture below. We do not want to use the classes/code that was generated from the Entity Engine Generator. So as you will see below, the "Code Generation Strategy" is set to None. Then you will see, if you go to the code behind file, that basically is an empty file. We will step in here and add our own classes.

 

 

5) Add another class file to your class library project.Name it DataAccess.cs. Inside there we will write our own plain classes that will reflect the model we have.

Inside the DataAccess.cs file type,

public class Company
  {
      public Company()
      {

          Employees = new List<Employee>();

      }

      public int CompanyID { getset; }
      public string CompanyName { getset; }
      public virtual List<Employee> Employees { getprivate set; }
  }

    public class Employee
    {
        public Employee()
        {

        }


        public int EmpID { getset; }
        public string EmpFirstName { getset; }
        public string EmpLastName { getset; }
        public string Email { getset; }
        public int CompanyID { getset; }
        public string Street { getset; }
        public string City { getset; }
        public string Country { getset; }
        public string PostalCode { getset; }
        public string Phone { getset; }
        public Company Company { getset; }


    }



public class CompanyEmployeesEntities:ObjectContext
    {
public  CompanyEmployeesEntities():base("name=CompanyEmployeesEntities")
            {

                ContextOptions.LazyLoadingEnabled = true;

            }

        public ObjectSet<Company>Companies
            {
                get{return CreateObjectSet<Company>();}

            }

        public ObjectSet<Employee>Employees
            {
                get{return CreateObjectSet<Employee>();}

            }

    
   }

 

6) Let me explain what I do in the code above.I create the classes Company and Employee bearing in mind they must have the same name as in my model.All the properties that I define inside my classes must have the same name and must have the same type as well.Inside the Company class, I am instantiating inside the constructor a list of Employees

 public Company()
      {

          Employees = new List<Employee>();

      }

 

 All the properties from the model must be represented in the class file. You can also add more properties if you want.

 Then after that I create the ObjectContext class.I am sure you have realised by now that this is the most important class in the EF paradigm. I also set the lazy loading option to true.

ContextOptions.LazyLoadingEnabled = true;

 

 7) So now we are ready to write a LINQ to Entities query to retrieve data from our model. Let's say that we want to get all the companies that their name starts with "Tr" and have more than 2 employees.

We want to display the company name and the Employee's first and last name.

In the Page_Load event handling routine of the Default.aspx page

 CompanyEmployeesEntities ctx = new CompanyEmployeesEntities();


var companies = from comp in ctx.Companies 
where comp.CompanyName.StartsWith("Tr") &&
 comp.Employees.Count >= 2select comp;


        foreach (var comp in companies)
        {
           
            Response.Write("<h2>" + comp.CompanyName + "</h2>");
            Response.Write("<br/>");
            foreach (Employee emp in comp.Employees)
            {

               
Response.Write("<strong><em>" + emp.EmpFirstName + " " + 
emp.EmpLastName + "</em></strong>");
Response.Write("<br/>");
            
            }
           
        }

 

8) Run your application (set breakpoints if you want) and see the results displayed on the screen.

If you do not want to type the code yourself for the POCO classes, you can download through the Extension Manager in Visual Studio(Tools->Extension Manager) ( from the Online Gallery go to Templates and select Database -> ADO.NET C# POCO Entity Generator) and generate the hand made classes (we wrote above) automatically.

Email me if you need the source code.

Hope it helps!!!

2 Comments

Comments have been disabled for this content.