Answered Finding a Navigation Property's Key

  • Friday, May 23, 2008 2:34 PM
     
     

    Hopefully this will be an easy question.

     

    In my model the EDM designer has (correctly) replaced a field that represents a foreign key with a Navigation Property. Unfortunately, the key is not a meaningless key. In fact it was designed as an optimisation as in most instances the relation does not need to be followed as the key is the most often used piece of data. So how do I access the value without loading the entity at the far end? I have found one method:

    Code Snippet
    int value = (int)entity.MyEntityReference.EntityKey.EntityKeyValues[0].Value;

     

     

    But that is obviously not as easy as it would have been if the field was still present and accessible:

    Code Snippet

    int value = entity.MyEntityId;

     

     

    I could (and probably will) add a property to the partial class to wrap this, but I just wondered if there is an easier way I have missed.

All Replies

  • Friday, May 23, 2008 4:22 PM
     
     Answered
    We've done the same thing, added a property to the partial class.  We also created an extension method to get the value:
    Code Snippet
    public static TValue GetId<TValue>(this EntityReference reference)
    {
         if (reference == null)

              {

               return default(TValue);

              }

              EntityKey key = reference.EntityKey;
              if (key != null)
              {
                    EntityKeyMember[] entityKeys = key.EntityKeyValues;
                    if (entityKeys.Length > 0)
                    {
                        return (TValue)entityKeys[0].Value;
                    }
              }

              return default(TValue);

    }


    and the added properties look like this:
    Code Snippet

    public int PartnerId
    {
    get { return PartnerReference.GetId<int>(); }
    }

    You could also add a setter that would set the EntityKey of the reference.  Note that the EntityKey of the reference will be null if the entity was loaded with MergeOption.NoTracking, so a 0 would be returned.
  • Friday, May 23, 2008 5:24 PM
     
     

    Many thanks, that worked a treat. I even added the property to my custom code generator!