[TestMethod] public void Test_Ef_Get_PK() { // Arrange DbContext db = new EfDbMapper(connectionString); var objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext; System.Data.Objects.ObjectSet<Product> set = objectContext.CreateObjectSet<Product>(); //Act IEnumerable<string> keyNames = set.EntitySet.ElementType.KeyMembers.Select(k => k.Name); // Assert Assert.AreEqual("ProductId", string.Join(",", keyNames.ToArray())); }
...is this:
[TestMethod] public void Test_Ef_Get_PK_via_pure_reflection() { // Arrange DbContext db = new EfDbMapper(connectionString); var objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext; Type t = typeof(Product); // anything that can be obtained during runtime MethodInfo m = objectContext.GetType().GetMethod("CreateObjectSet", new Type[] { }); MethodInfo generic = m.MakeGenericMethod(t); object set = generic.Invoke(objectContext, null); PropertyInfo entitySetPI = set.GetType().GetProperty("EntitySet"); System.Data.Metadata.Edm.EntitySet entitySet = (System.Data.Metadata.Edm.EntitySet) entitySetPI.GetValue(set, null); // Act IEnumerable<string> keyNames = entitySet.ElementType.KeyMembers.Select(k => k.Name); // Assert Assert.AreEqual("ProductId", string.Join(",", keyNames.ToArray())); }
This was of great help, i was looking exactly on how to do this!
ReplyDeleteGood work!
Thanks a lot
Nice Post!!!
ReplyDeleteThat's what i was looking for!
thank you !
ReplyDelete