要在Entity Framework4.0上获取数据库表名,我这样做:
ObjectSetInstance.EntitySet.ToString()在Entity Framework4.1上有没有办法做到这一点?
发布于 2011-07-08 20:51:54
尝试如下所示:
string name = (context as IObjectContextAdapter).ObjectContext.CreateObjectSet<MyClass>().EntitySet.Name;发布于 2012-03-20 02:26:02
DbContext和ObjectContext的扩展方法
public static class ContextExtensions
{
public static string GetTableName<T>(this DbContext context) where T : class
{
ObjectContext objectContext = ((IObjectContextAdapter) context).ObjectContext;
return objectContext.GetTableName<T>();
}
public static string GetTableName<T>(this ObjectContext context) where T : class
{
string sql = context.CreateObjectSet<T>().ToTraceString();
Regex regex = new Regex("FROM (?<table>.*) AS");
Match match = regex.Match(sql);
string table = match.Groups["table"].Value;
return table;
}
}使用ObjectContext对象:
ObjectContext context = ....;
string table = context.GetTableName<Foo>();使用DbContext对象:
DbContext context = ....;
string table = context.GetTableName<Foo>();更多信息请点击此处:
Entity Framework: Get mapped table name from an entity
发布于 2015-04-11 06:51:12
从EF6.1开始,this文章中探索的解决方案展示了如何使用新公开的元数据来实现这一点,不应该要求初始化数据库,也不应该依赖于用来设置表名的方法。
https://stackoverflow.com/questions/6598857
复制相似问题