是否有一种使用元数据工作空间在给定DbContext
和实体type
上获取鉴别符值的方法?我希望能找到类似https://romiller.com/2014/04/08/ef6-1-mapping-between-types-tables/这样的东西。
用法将是:
public class MyContext : DbContext
{
public DbSet<Foo> Foo { get; set; }
}
public class FooBase
{
}
public class Foo : FooBase
{
}
public void Test()
{
// should be "Foo"
var discriminator = GetDiscriminatorValue(typeof(Foo), new MyContext());
}
public static string GetDiscriminatorValue(Type type, DbContext context)
{
//...
}
答案 0 :(得分:0)
我认为我可以使用以下方法解决此问题。
public static string GetDiscriminatorValue(this DbContext context, Type type)
{
var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
// Get the mapping between CLR types and metadata OSpace
var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
// Get the entity type from the model that maps to the CLR base type of the given type
var entityType = metadata
.GetItems<EntityType>(DataSpace.OSpace)
.Single(e => objectItemCollection.GetClrType(e) == type.BaseType);
// Get the entity set that uses this entity type
var entitySet = metadata
.GetItems<EntityContainer>(DataSpace.CSpace)
.Single()
.EntitySets
.Single(s => s.ElementType.Name == entityType.Name);
// Find the mapping between conceptual and storage model for this entity set
var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace)
.Single()
.EntitySetMappings
.Single(s => s.EntitySet == entitySet);
// Find the value condition (discriminator) that the given type is mapped
var discriminator = mapping
.EntityTypeMappings
.Single(e => e.EntityType?.Name == type.Name)
.Fragments
.Single()
.Conditions
.OfType<ValueConditionMapping>()
.Single();
return (string)discriminator.Value;
}