Wednesday, February 24, 2010

Binding foreignkeys and EF's entity by using EntityDataSource to Bindable Controls such as FormView, GridView

Here is a simple case. You have a Client table and a lkpClientType table and they have a referential relationship by lkpClientTypeID. And you want to show the ClientTypeID of the Client table in a data bindable control. How can you do it?

Here is a procedure to follow:
  1. Create a EntityDataSource
  2. Select Client as your source entity. (I assume that you know how to setup a edmx file.)
  3. In VS 2008 designer, select the EDS and hit 'F4' to see a properties window.
  4. Look for an include property field and type "lkpClientType"
  5. Now in your bindable property value do something like <%#Bind("lkpClientType.ClientTypeID")%>

How to include a foreignkey in your own EF's entityobject?

If your EntityModel name is MyEntities and in your model, if you have Client class inherits from entityobject having a navigation or foreignkey relationship with lkpClientType class also inherits from entityobject, create a partial class like this.


   1:  Partial Public Class Client
   2:   
   3:      Public Property ClientTypeID() As Nullable(Of Integer)
   4:          Get
   5:              If lkpClientTypeReference Is Nothing Then
   6:                  Return Nothing
   7:              End If
   8:   
   9:              If lkpClientTypeReference.EntityKey Is Nothing Then
  10:                  Return Nothing
  11:              End If
  12:              Return lkpClientTypeReference.EntityKey.EntityKeyValues(0).Value
  13:          End Get
  14:   
  15:          Set(ByVal value As Nullable(Of Integer))
  16:              If value.HasValue Then
  17:                  ' To notify others listening that the property is changing
  18:                  OnPropertyChanging("ClientTypeID")
  19:                  lkpClientTypeReference.EntityKey = New EntityKey("MyEntities.lkpClientType", _
  20:                               New EntityKeyMember() {New EntityKeyMember("ClientTypeID", DirectCast(value.Value, Object))})
  21:                  OnPropertyChanged("ClientTypeID")
  22:              End If
  23:          End Set
  24:      End Property
  25:   
  26:  End Class
Once done creating the partial class and compiling, following query will include your foreignkey as well in your result set of Client:

Dim aClient= (from c in MyEntities.Client where c.ClientID = 1012 select c).First()
System.WriteLine(aClient.ClientTypeID)
Or
Var aClient= (from c in MyEntities.Client where c.ClientID = 1012 select c).First()
Sytem.WriteLine(aClient.ClientTypeID)