How to get ObjectSet's entity key name?

后端 未结 7 1391
悲哀的现实
悲哀的现实 2020-12-29 00:08

I\'ve created a generic ObjectSet in my generic repository.

What I would like to get is the name of the EntityKey of ObjectS

7条回答
  •  梦毁少年i
    2020-12-29 00:33

    Generic:

    public class GenericoRepositorio : IGenericoRepositorio where T : class
    {
        protected readonly ObjectSet ObjetoSet;
        protected readonly ModeloContainer Contexto;
    
        public GenericoRepositorio(ModeloContainer contexto)
        {
            Contexto = contexto;
            ObjetoSet = Contexto.CreateObjectSet();
        }
    
        public T Carregar(int id)
        {
            object objeto;
            Contexto.TryGetObjectByKey(GetEntityKey(ObjetoSet, id), out objeto);
            return (T)objeto;
        }
    
        private static EntityKey GetEntityKey(ObjectSet objectSet, object keyValue) where T : class
        {
            var entitySetName = objectSet.Context.DefaultContainerName + "." + objectSet.EntitySet.Name;
            var keyPropertyName = objectSet.EntitySet.ElementType.KeyMembers[0].ToString();
            var entityKey = new EntityKey(entitySetName, new[] { new EntityKeyMember(keyPropertyName, keyValue) });
            return entityKey;
        }
    }
    

提交回复
热议问题