Sunday, June 10, 2012

Get Entity Framework class' primary key property names during runtime

The runtime version of getting class' primary key property names ...

[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()));
}

3 comments:

  1. This was of great help, i was looking exactly on how to do this!

    Good work!

    Thanks a lot

    ReplyDelete
  2. Nice Post!!!

    That's what i was looking for!

    ReplyDelete