Saturday, August 30, 2008

For some background, check out a previous post called "Where's my Foreign Key?"

I came across a scenario where I have a foreign key for an entity in the form of an ID. And the scenario is in a web page. I need to turn that ID into an EntityReference, but I don't think that it's fair to ask the UI developer to know enough about EF that they should have to know how to create an EntityKey, much less know about EntityReferences.

Rather than force them to pass the ID up to the business layer, I finally gave in added foreign key support into the entities that I'm using in this web solution.

I've also gotten sick of having to write this code in many other places where I am creating relationships through EntityReferences. Especially when I make typos and then get this error at runtime.

Rather than futz around with a generic solution, I just manually created these keys in the partial classes for my entities.

As long as I was setting the EntityReference, I thought I would let the property provide the key on demand as well.

Here's an example from the Address class.

Public Property ContactID() As Integer
     Get
         If ContactReference.EntityKey.EntityKeyValues.Count > 0 Then
             Return CType(ContactReference.EntityKey.EntityKeyValues(0).Value, Integer)
         Else
             Return Nothing
         End If
     End Get
     Set(ByVal value As Integer)
         If value > 0 Then
             ContactReference.EntityKey = New EntityKey("myEntities.Contacts", "ContactID", value)
         End If
     End Set
 End Property
Saturday, August 30, 2008 2:20:25 PM (Eastern Standard Time, UTC-05:00)  #     |  Comments [0]  |