Entity Framework Count Child Entities

Expanding on the post “Entity Framework Filter Child Entity“, I finally figured out how to get a GridView to show the count of child records. Unfortunately I am returning the whole set of entities and doing a Count on them. It’s not a problem in this case. I’m just happy it works.

Dim query = (From x In db.OrderChecklistItems Where x.Enabled = True Order By x.Enabled Descending, x.ItemText Select OCI = x, _
            
OD = From y In x.OrderDocuments Where y.OrderID = OrderID, _
            
CS = From z In x.OrderChecklistSelections)
 
Dim customers = From item In query.ToList Select item.OCI
 
GridView1.DataSource = customers
GridView1.DataBind()

Then in the GridView:

Eval("OrderChecklistSelections.Count")

Entity Framework Filter Child Entity

I was looking for a way to filter child entities with eager loading. I ran into this useful blog post by Beth Massi on the subject.

Here is the code I ended up using. It doesn’t work with server-side paging, but I didn’t need it in this case.

Dim query = (From x In db.OrderChecklistItems Where x.Enabled = True Select OCI = x, _
             
OD = From y In x.OrderDocuments Where y.OrderID = OrderID)

Dim customers = From item In query.ToList Select item.OCI

GridView1.DataSource = customers

Entity Framework GridView RowDataBound

I found it tricky to get actual entities in the GridView RowDataBound event.

Per Diego Vega’s post here, this may only happen because I am using the EntitySetName property of the EntityDataSource.

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
            Dim descriptor As ComponentModel.ICustomTypeDescriptor = e.Row.DataItem

If descriptor IsNot Nothing Then
                Dim prop = descriptor.GetProperties().Cast(Of ComponentModel.PropertyDescriptor)().First()

Dim Order As Order = DirectCast(descriptor.GetPropertyOwner(prop), Order)

Response.Write(“Order Number:” & Order.OrderNumber)
End If
End If
End Sub