我使用Entity Framework 4.1和Code First方法。我能够获取我的实体的存储模型类型和列名称:
var items = context.ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.SSpace);
foreach (var i in items)
{
Console.WriteLine("Table Name: {0}", i.Name);
Console.WriteLine("Keys:");
foreach (var key in i.KeyMembers)
Console.WriteLine("\t{0} ({1})", key.Name, key.TypeUsage.EdmType.FullName);
Console.WriteLine("Members:");
foreach (var member in i.Members)
Console.WriteLine("\t{0} ({1})", member.Name, member.TypeUsage.EdmType.FullName);
}
我需要的是获取实体映射到的真实表名。有不同的方法来指定(通过使用Fluent-API .ToTable(),DataAnnotation [TableAttribute])。
有没有通用的方法来获取这些信息?
答案 0 :(得分:10)
我找到获取表名的最简单方法如下:
var tables = Context.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace)
.Where(x => (x.MetadataProperties.Contains("NamespaceName") ? String.Compare(x.MetadataProperties["NamespaceName"].Value.ToString(), "Model", true) == 0 : false)
&& !x.MetadataProperties.Contains("IsForeignKey")
&& x.MetadataProperties.Contains("KeyMembers"));
这将为您提供表格实体。
然后您可以执行以下操作来提取名称:
foreach (var item in tables)
{
EntityType itemType = (EntityType)item;
String TableName = itemType.Name;
}
请注意,如果您复制上下文,则需要撤消该上下文。
答案 1 :(得分:9)
EF 6.1,代码优先:
public static string GetTableName<T>(this DbContext context) where T : class
{
ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
return objectContext.GetTableName(typeof(T));
}
public static string GetTableName(this DbContext context, Type t)
{
ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
return objectContext.GetTableName(t);
}
private static readonly Dictionary<Type,string> TableNames = new Dictionary<Type, string>();
public static string GetTableName(this ObjectContext context, Type t)
{
string result;
if (!TableNames.TryGetValue(t, out result))
{
lock (TableNames)
{
if (!TableNames.TryGetValue(t, out result))
{
string entityName = t.Name;
ReadOnlyCollection<EntityContainerMapping> storageMetadata = context.MetadataWorkspace.GetItems<EntityContainerMapping>(DataSpace.CSSpace);
foreach (EntityContainerMapping ecm in storageMetadata)
{
EntitySet entitySet;
if (ecm.StoreEntityContainer.TryGetEntitySetByName(entityName, true, out entitySet))
{
result = entitySet.Schema + "." + entitySet.Table;//TODO: brackets
break;
}
}
TableNames.Add(t,result);
}
}
}
return result;
}
答案 2 :(得分:1)
您还可以通过其他方式获取EDM表名称
public static string GetTableName<T>(this ObjectContext context) where T : EntityObject
{
var entities= context.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace).Where(b => b.BuiltInTypeKind == BuiltInTypeKind.EntityType);
foreach (System.Data.Metadata.Edm.EntityType item in entities)
{
if(item.FullName==typeof(T).FullName)
return item.Name;
}
return String.Empty;
}