Entity Framework Load Related Singleton Reference, Delete

1. Simple Load and Bind Example

[sourcecode language=”vb.net”]
Dim AdventureWorks_DataEntity as New AdventureWorksDataEntities()
Dim Query = From e IN AdventureWorks_DataEntity.Employee
Gridview.DataSource = query
Gridview.databind()
[/sourcecode]

2. Load Related Data in Entity Framework

[sourcecode language=”vb.net”]
Dim AdventureWorks_DataEntity as New AdventureWorksDataEntities()
For Each employee in AdventureWorks_DataEntity.Employee
Dim Li as New ListItem()
Li.Text = employee.EmployeeID & ” ”

If (Not employee.EmployeePayHistory.IsLoaded) Then
employee.EmployeePayHistory.Load()
End if

For Each pay In employee.EmployeePayHistory
li.Text &= “Pay Rate: ” & pay.Rate & ” ”
Next pay

BulletedList1.Items.Add(li)
Next employee
[/sourcecode]

Another option for loading related data is to use the “include”. This will eager load the children EmployeePayHistory for the employees.
[sourcecode language=”vb.net”]
Dim AdventureWorks_DataEntity as New AdventureWorksDataEntities()
Dim query = from e in employee.Include(“EmployeePayHistory”)
[/sourcecode]

3. Singleton Reference (One to One) to get relationship use “objectReference”

[sourcecode language=”vb.net”]
var personTwo = (from p in context.Person WHERE p.Student != null select p).first();
personTwo.StudentReference.Load()

‘(one to Many relationship)
personTwo.Student.Load()
[/sourcecode]

4. Delete Entity

[sourcecode language=”C#”]
try
{
using (var context = new AdventureWorks2008Entities())
{
var prod = context.Products.Where(p => p.ProductID == 1005).First();
context.DeleteObject(prod);
context.SaveChanges();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException.Message);
}

[/sourcecode]

5.ATTACHING and DETACHING

If calls across assembly layer, it’s detached when accessed.

<asp:EntityDataSource Include=”Student”>

<asp:listview Id=”listView” runat=”server” DataKeyNames=”PersonID” DataSourceID=”personDataSource” Insert …

<%# Eval(“Student.Year”) %>

<asp:ObjectDataSource (Develop new class i.e. people.cs as partial class)

SchoolEntities context = new SchoolEntities();

return context.Person.INclude(“Student.Where(p => p.enrollmentdate.hasvalue.tolist();

6.POCO

Still to come…

Author: Travis Gneiting

Passionate Professional .NET Developer