Wednesday, February 24, 2010

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)

No comments:

Post a Comment