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>();