tags:

views:

444

answers:

2

How to get the value of EntityKey?

I tried:

String x = Customer.EntityKey.EntityKeyValues[0].Value;

String x = Customer.EntityKey.EntityKeyValues[0].Value.ToString();

String x = Customer.EntityKey.EntityKeyValues;

String x = Customer.EntityKey.EntityKeyValues.ToString();

Ended up with: Object reference not set to an instance of an object.

Please help. Thanks

+1  A: 

As you reported that you're getting an Object reference not set to an instance of an object, you might want to check for a null reference;

String x = (Custormer == null ? null :
              Customer.EntityKey == null ? null :
                Customer.EntityKey.EntityKeyValues.Length == 0 ? null :
                  Customer.EntityKey.EntityKeyValues[0].Value);
Paulo Santos
Thanks you!!!!!!!!!!!!!
noobplusplus
A: 

What about this scenario: I have a foreign key table ("Property") and another primary key table ("PropertyType"). In the DB proper data exists. I have created a partial "Property" class to get\set the "PropertyTypeId" forein key column like this:

public partial class Property : global::System.Data.Objects.DataClasses.EntityObject
{
       [global::System.Runtime.Serialization.DataMemberAttribute()]
        public int PropertyTypeId
        {
            get
            {
                string value = this.PropertyTypeReference.EntityKey.EntityKeyValues[0].Value.ToString();
                return int.Parse(value);
            }
            set
            {
                this.PropertyTypeReference.EntityKey = new System.Data.EntityKey("RealestateEntities.PropertyTypeSet", "PropertyTypeId", global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value));
            }
        }
}

It was working fine for long. But suddenly I started to get and error: "Object reference not set to an instance of an object." in the first line of the get method. Was wondering what might be causing the problem.

Rahat