locked
How to get Primary Key info from DbContext ? RRS feed

  • Question

  • I am using entityframework 6 codefirst , how can i get the primary key of entity? Or get the schemas info?
    Thursday, May 26, 2016 1:56 AM

Answers

  • Hi Andrewc9,

    According to your description, Do you want to retrieve the primary key name form entity class? if so, we could use the following code to achieve it.

    using (var db = new DemoContext())
                {
                    var objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext;
                    ObjectSet<Song> set = objectContext.CreateObjectSet<Song>();
                    //Act
                    IEnumerable<string> keyNames = set.EntitySet.ElementType.KeyMembers.Select(k => k.Name);
                    Console.WriteLine("{0}", string.Join(",", keyNames.ToArray()));
    
                    Console.ReadKey();
    }

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, May 27, 2016 1:15 AM