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!!!
Comments
Anonymous
June 02, 2010
above code will not run - need to add property for the foriegn key DeptId in EmpDeptAnonymous
June 02, 2010
@Peitro, Thanks for your comment. The code is tested at my end and works. I have used the concept of Navigation property rather than the Foriegn Key.