Entity Framework 4: How to find the primary key?

前端 未结 4 669
萌比男神i
萌比男神i 2020-11-28 11:12

I am trying to create a generic method using EF4 to find the primary key of an object.

example

public string GetPrimaryKey()
{
    ...
}
         


        
4条回答
  •  春和景丽
    2020-11-28 12:13

    There is a property on each EF4 entity called EntityKey which contains an array of EntityKeyValues (array is there in case of compound key).

    You could reference this directly on your entity instance or create a generic helper method that does this under the covers. If I can test-drive some sample code, I'll post it up here.

    Edit: The EntityKeyValue is a KeyValuePair where the key is the primary key field of the entity and the value is the associated value.

    E.g., I have an entity called Company whose primary key is the field Symbol.

    var firstCompany = (from c in context.Companies select c).FirstOrDefault();
    var kvp = firstCompany.EntityKey.EntityKeyValues[0];
    // kvp shows {[Symbol, FOO]}
    

    In my sandbox, I noticed this property was null when I created the entity in code. But once I read the entity from the database, it was correctly populated. So, it appears that the EF4 concept of a primary key only comes in to play once it hits the database. Although, you are free to set it explicitly ahead of time, if you wish.

提交回复
热议问题