How to get ObjectSet's entity key name?

后端 未结 7 1375
悲哀的现实
悲哀的现实 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条回答
  •  北海茫月
    2020-12-29 00:22

    I looked a while ago for a nice way to do this and failed to find one. I generally end up building a GetEntityByKey extension method somewhere and within that, contatenating strings to build Entity Keys for TryGetObjectByKey calls. The general idea for building the entity key goes something like this:

    internal class Program
    {
        private static void Main(string[] args)
        {
            var dc = new AdventureWorksLT2008Entities();
            object c;
            dc.TryGetObjectByKey(GetEntityKey(dc.Customers, 23), out c);
            var customer = c as Customer;
            Console.WriteLine(customer.EmailAddress);
        }
    
        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;
        }
    }
    

    You may be able to do something similar. This example assumes a single field per EntityKey for simplicity - for multiple value keys you would need to do something slightly more sophisticated with ObjectSet.ElementType.KeyMembers and pass all your keys into the EntityKey constructor.

提交回复
热议问题