Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first EntityKey Name for an Entity in EF4

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?

like image 297
Ahmed Magdy Avatar asked Jan 21 '23 16:01

Ahmed Magdy


1 Answers

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.

like image 99
Ahmed Magdy Avatar answered Feb 03 '23 17:02

Ahmed Magdy