Penguen
Penguen

Reputation: 17298

How can i write generic Primary key finder on EntityKey?

i think that below codes is very useful. But i try to create EntityKEy. i used:

 EntityKey key = new EntityKey(entitySetKEYName, "XTableId", id);

But i dont want to use this. my table PRIMARYID YtableId,ZTableId, etc... How can i write this:
 EntityKey key = new EntityKey(entitySetKEYName, Find().PrimaryKEY, id);

       public T GetByPrimaryKey<T>(int id)
        {
            string entitySetName = _context.MetadataWorkspace.GetEntityContainer(_context.DefaultContainerName, DataSpace.CSpace).BaseEntitySets.
                Where(q => q.ElementType.Name == typeof(T).Name).FirstOrDefault().Name;
            string entitySetKEYName = string.Format("{0}.{1}", _context.DefaultContainerName, entitySetName);
            EntityKey key = new EntityKey(entitySetKEYName, "XTableId", id);

            return (T)_context.GetObjectByKey(key);
        }

HOW CAN AUTOMATICALLY DETECT PRIMARY KEY????????????????

Upvotes: 2

Views: 2288

Answers (1)

Alex Burtsev
Alex Burtsev

Reputation: 12698

First,PK is not necessary Int32, it can be Guid or even multi property complex key, so generic method should except Object as PK... Here is my pretty ugly variant, but it does the job, though it need proper testing.

    static void Main(string[] args)
    {
        var entity = GetEntityByKey<Entity>(Guid.Empty);
    }
    private static T GetEntityByKey<T>(object key) where T : class 
    {
        using (var context = new ObjectContext("Name=ModelContainer"))
        {
            var set = context.CreateObjectSet<T>().EntitySet;
            var pk = set.ElementType.KeyMembers[0]; // careful here maybe count can be o or more then 0
            EntityKey entityKey = new EntityKey(set.EntityContainer.Name+"."+set.Name, pk.Name, key);
            return (T)context.GetObjectByKey(entityKey);
        }
    }

Upvotes: 2

Related Questions