Entity Framework 4: How to find the primary key?

前端 未结 4 710
萌比男神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:19

    this seems needlessly long? I have had the same need, and using the suggestions above (by SethO and denis_n), i am using:

            //get the primary key field name and location for the table
            var primaryFieldName = entry.EntitySet.ElementType.KeyMembers[0].Name ;
            int primaryFieldLocation = entry.CurrentValues.GetOrdinal(primaryFieldName);
            //gets the value pair for the primary key (returns field name + value)
            var primaryField = entry.EntityKey.EntityKeyValues[primaryFieldLocation];
            String primaryFieldValue = primaryField.Value.ToString();
    

    Hope this helps anyone who is interested

提交回复
热议问题