Category Archives: Entity framework

Entity framework

What is Data Concurrency and Types of Concurrency Control in ADO.NET.

When multiple users attempt to modify data at the same time, controls need to be established in order to prevent one user’s modifications from adversely affecting modifications from simultaneous users. The system of handling what happens in this situation is called concurrency control.

Types of Concurrency Control
Three common ways to manage concurrency in a database:

  • Pessimistic concurrency control: A row is unavailable to users from the time the record is fetched until it is updated in the database.
  • Optimistic concurrency control: A row is unavailable to other users only while the data is actually being updated. The update examines the row in the database and determines whether any changes have been made. Attempting to update a record that has already been changed results in a concurrency violation.
  • “Last in wins”: A row is unavailable to other users only while the data is actually being updated. However, no effort is made to compare updates against the original record; the record is simply written out, potentially overwriting any changes made by other users since you last refreshed the records.

What is the difference between POCO, code first and simple EF approach?

All these three approaches define how much control you want on your Entity frame work code. Entity framework is an OR MAPPER it generates lot of code, it creates your middle tier (Entity) and Data access layer (Context).

  • In Simple entity framework everything is auto generated and so you need the EDMX XML file as well.
  • POCO is semi-automatic so you have full control on the entity classes but then the context classes are still generated by the EDMX file.
  • In code first you have complete control on how you can create the entity and the context classes. Because you are going to manually create these classes you do not have dependency on the EDMX XML file.

How to implement POCO in entity framework?

To implement POCO is a 3 step process:-

  • Go to the designer and make the code generation strategy to NONE. This step means that you would be generating the classes with your own hands rather than relying on EF auto code generation.
  • So now that we have stopped the auto generation of code , we need to create the domain classes manually. So add a class file and create the domain classes like the one “Customer” class we have created.
    public class Customer 
    { 
        private string _customerName; 
        public string CustomerName 
        { 
           get 
              { 
                 return _customerName; 
              } 
           set 
              { 
                 _customerName = value; 
              } 
       }
      private int _Customerid; 
      public int Customerid 
      { 
       get 
        { 
          return _Customerid; 
        } 
       set 
        { 
           _Customerid = value; 
        } 
      } 
    }
    
  • Write your Context layer code inheriting from the “ObjectContext”. This code you can copy paste from the behind code of EF also before disabling autogeneration.
    public partial class Test123Entities : ObjectContext
    {
        public Test123Entities()
            : base("name=Test123Entities", "Test123Entities")
        {
            this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated();
        }
        partial void OnContextCreated();
        public ObjectSet<Customer> Customers
        {
            get
            {
                if ((_Customers == null))
                {
                    _Customers = base.CreateObjectSet<Customer>("Customers");
                }
                return _Customers;
            }
        }
        private ObjectSet<Customer> _Customers;
        public void AddToCustomers(Customer customer)
        {
            base.AddObject("Customers", customer);
        }
    }
    

And finally you can use the above code in your client as you where using your EF normally.

Test123Entities oContext = new Test123Entities(); 
List<Customer> oCustomers = oContext.Customers.ToList<Customer>();

What are POCO classes in Entity framework?

POCO means Plain old C# object. When EDMX creates classes they are cluttered with lot of entity tags. For instance below is a simple customer class generated using entity framework. Many times we would like to use simple .NET classes and integrate the same with entity framework.

Entity framework allows the same. In other words you can create a simple .NET class and use the entity context object to load your simple .NET classes.

How can we turn off lazy loading?

The opposite of lazy loading is eager loading. In eager loading we load the objects beforehand. So the first thing is we need to disable lazy loading by setting “LazyLoadingEnabled” to false.

context.ContextOptions.LazyLoadingEnabled = false;

So now we have to explicitly tell EF what objects we want to load by using the “include” function. Below is a simple sample code where we tell EF to load customer as well as address objects by using the “include” function.
So now the customer object and the related address objects will be loaded in one query rather than multiple queries.

var employees = context.Customers.Include("Addresses").Take(5);

Can you explain lazy loading in a detailed manner ?

Lazy Loading is a concept where we load objects on demand rather than loading everything in one go.

Consider a situation where you have 1 to many relationships between “customer” and “address” object.

Now let’s say you are browsing the customer data but you do not want address data to be loaded that moment. But the time you start accessing the address object you would like to load address data from database.

Entity framework has the lazy loading behavior by default enabled. For instance consider the below code. When we are doing “foreach” on the customer object address object is not loaded. But the time you start doing “foreach” on the address collection address object is loaded from SQL Server by firing SQL queries.

So in simple words he will fire separate query for each address record of the customer which is definitely not good for large number of records.

MyEntities context = new MyEntities(); 
var Customers = context.Customers.ToList(); 
foreach (Customer cust in Customers) // In this line no address object loaded 
{ 
  foreach(Address add in cust.Addresses)
    {
    }// Address object is loaded here 
}

How can we read records using entity framework classes?

In order to browse through records you can create the object of the context class and inside the context class you will get the records.

For instance in the below code snippet we are looping through list of customer object collection. This customer collection is a output given by the context class “CustomermytextEntities”.

CustomermytestEntities obj = new CustomermytestEntities(); 
foreach (Customer objCust in obj.Customers) 
{
}

What is the importance of T4 in Entity framework?

T4 files are heart in EF code generation. So the T4 code templates read the EDMX XML file and generate C# behind code. This C# behind code is nothing but your entity and context classes.
T4Importance

 

If you create a project using VS 2012, you will see the following hierarchy. At the top we have the EDMX file, followed by the TT or T4 file and then the .CS code file.

T4Importance1

What are T4 templates?

T4 (Text template transformation toolkit) is template based code generation engine. So you can go and write C# code in T4 templates ( .tt is the extension) files and those c# codes execute to generate the file as per the written C# logic.

For instance the below T4 c# code:-

<#@ template language=“C#” #> Hello <# Write(”World!”) #>

Will generate the following C# output:-
Hello
World !