How to get first EntityKey Name for an Entity in EF4

后端 未结 4 1279
死守一世寂寞
死守一世寂寞 2021-02-06 15:21

How can I get the 1st EntityKey name for an Entity for Entity Framework 4 because I\'m building a repository system and I wanted to get an item by Id (which is the primary key o

4条回答
  •  独厮守ぢ
    2021-02-06 15:56

    Try this:

    /// 
    /// Gets the entity key for the POCO Entity type.
    /// 
    /// The entity.
    /// 
    private EntityKey GetEntityKey(TEntity entity)
    {
        ReadOnlyMetadataCollection keyMembers =
            this.ObjectSet.EntitySet.ElementType.KeyMembers;
    
        var entityKeyMembers = new List();
    
        //Construct the entity key for the POCO Entity type object.
        foreach (EdmMember keyMember in keyMembers)
        {
            object keyMemberValue = entity.GetType().GetProperty(keyMember.Name).GetValue(entity, null);
            entityKeyMembers.Add(new EntityKeyMember(keyMember.Name, keyMemberValue));
        }
    
        //Create the Entity key for our POCO Entity type object.
        return new EntityKey(this.ObjectSource.DefaultContainerName
            + "." + this.ObjectSet.EntitySet.Name, entityKeyMembers);
    }
    

    objectsource is objectcontext.

提交回复
热议问题