Reputation: 41539
I'm using EF 4.1 Code First, with a Fluent Mapping:
Entity:
public class MyClass
{
public int MyClassID { get; set; }
public string Name { get; set; }
}
Mapping:
public class MyClassMapping: EntityTypeConfiguration<MyClass>
{
public MyClassMapping()
{
Map(t => t.ToTable("MyClass"))
.HasKey(t => t.MyClassID);
Property(t => t.MyClassID)
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.Name)
.IsRequired()
.HasMaxLength(200);
}
}
Given this configuration (and a number of similar declarations/mappings for other entities), if I know the type of the entity class (ie MyClass
) is it possible to get the Type and Name of the key property of the entity class? - Since I've defined it in the mapping, shouldn't I be able to get this back from either IDbSet
for MyClass
or my DbContext
derived Entity container?
I'm not interested in just assuming that keyname = classname + "ID"
or similar - how is it done properly from the mappings?
Upvotes: 0
Views: 732
Reputation: 32437
You need to access the MetadataWorkspace
public class MyContext : DbContext
{
public void Test()
{
var objectContext = ((IObjectContextAdapter)this).ObjectContext;
var mdw = objectContext.MetadataWorkspace;
var items = mdw.GetItems<EntityType>(DataSpace.CSpace);
foreach (var i in items)
{
Console.WriteLine("Class Name: {0}", i.Name);
Console.WriteLine("Key Property Names:");
foreach (var key in i.KeyMembers)
{
Console.WriteLine(key.Name);
}
}
}
Upvotes: 4