How to get first EntityKey Name for an Entity in E

2019-03-21 14:55发布

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 oin EF is the 1st entitykey for the entity)

I'm using this code

public virtual TEntity GetById(string keyName, Guid entityId)
        {
            var entityKey = new EntityKey(this.QualifiedEntitySetName, keyName, entityId);
            object entity;
            return this.Context.TryGetObjectByKey(entityKey, out entity) ? entity as TEntity : null;
        }

I want to get the entity key name dynamic. Can anyone help me with this issue?

4条回答
我只想做你的唯一
2楼-- · 2019-03-21 15:40

You can get the Entity Key members collection from MetaDataWorkspace using the following code:

ReadOnlyCollection keyMembers = db.MetadataWorkspace.GetType("", "Entity_Namespace", System.Data.Metadata.Edm.DataSpace.CSpace).MetadataProperties["KeyMembers"].Value as ReadOnlyCollection;

查看更多
霸刀☆藐视天下
3楼-- · 2019-03-21 15:44

var keyName = this.Context .MetadataWorkspace .GetEntityContainer(this.Context.DefaultContainerName, DataSpace.CSpace) .BaseEntitySets .First(meta => meta.ElementType.Name == this.entityName) .ElementType .KeyMembers .Select(k => k.Name) .FirstOrDefault();

I know it looks too much but u I wanted to get it by having the Entity Name.

查看更多
Ridiculous、
4楼-- · 2019-03-21 15:51

Try this:

/// <summary>
/// Gets the entity key for the POCO Entity type.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns></returns>
private EntityKey GetEntityKey(TEntity entity)
{
    ReadOnlyMetadataCollection<EdmMember> keyMembers =
        this.ObjectSet.EntitySet.ElementType.KeyMembers;

    var entityKeyMembers = new List<EntityKeyMember>();

    //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.

查看更多
闹够了就滚
5楼-- · 2019-03-21 15:56
public static string GetPrimaryKeyName(this object entity)
   {
       var prop = entity.GetType().GetProperties().Where(x =>x.GetCustomAttributes(false).Where(y => y is ColumnAttribute&&((ColumnAttribute)y).IsPrimaryKey == true).Any()).FirstOrDefault();
          if (prop != null)
              return prop.Name;
          return string.Empty;

   }
查看更多
登录 后发表回答