ADO.NET Entity Framework 4.0 : POCO – The Code Only Approach

POCO in ADO.NET Entity Framework 4.0 has been discussed in many places. Here I am not going to talk about it. However, I created a small sample to demonstrate the capability of POCO in much more cleaner “code-only” approach.

<<Apology for this blog post issue>>. There were some images, due to which it was not showing up. I will add them later.

I am using a small test database with two tables,

Dept

====

DeptId

DeptName

EmpDept

=======

EmpId

EmpName

DeptId FK

I have created one ADO.NET Entity Framework Model

Now, to have POCO in-place I removed the Custom Tool property of the model to blank from “EntityModelCodeGenerator

Now, wrote the below code.

//Class Dept

public class Dept

{

    public Dept()

    {

        EmpDepts = new List<EmpDept>();

    }

    public int DeptId { get; set; }

    public string DeptName { get; set; }

   

    //Navigation Property of EmpDepts

    public virtual List<EmpDept> EmpDepts { get; private set; }

}

//EmpDept class

public class EmpDept

{

    public int EmpId { get; set; }

    public string EmpName { get; set; }

    //Navigation Property of EmpDepts

    public Dept Dept { get; set; }

}

public class TestDBEntities : ObjectContext

{

    //Base class constructor initializes with connection string

    public TestDBEntities()

        : base("name=TestDBEntities")

    {

        ContextOptions.LazyLoadingEnabled = true;

    }

    public IObjectSet<EmpDept> EmpDepts

    {

        get { return CreateObjectSet<EmpDept>(); }

    }

    public IObjectSet<Dept> Depts

    {

        get { return CreateObjectSet<Dept>(); }

    }

}

 

Now in the main method it supports Lazy Loading as well.

 

static void Main(string[] args)

{

    using (var ctx = new TestDBEntities())

    {

        var q = from c in ctx.Depts

                select c;

        foreach (var k in q)

        {

            Console.WriteLine(k.DeptName);

            Console.WriteLine(k.EmpDepts.Count);

        }

    }

}

 

Namoskar!!!