【问题标题】:ef code first: get entity table name without dataannotationsef代码优先:获取不带数据注解的实体表名
【发布时间】:2011-10-23 21:44:49
【问题描述】:

有没有办法获取用 DbModelBuilder 定义的表信息?

类似:

entity.GetType().GetTableName()

最大

编辑:

id 喜欢实现以下

public static class Helper
{
  public string GetTableName(Type type) {
    // ??
  }
}

现在我想按类型获取表名

var type = someEntity.getType();
var sql = "delete from " + Helper.GetTableName(type) + " where id in (...)"

【问题讨论】:

标签: c# linq ef-code-first


【解决方案1】:

我能想象的唯一解决方案是反射。在这里

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // model mappings

    base.OnModelCreating(modelBuilder);

    // table mapping
    var config = modelBuilder.Configurations
        .GetPrivateFieldValue("_modelConfiguration")
        .GetPrivateFieldValue("ActiveEntityConfigurations");

    var mapping = new Hashtable();
    foreach (var c in (IEnumerable)config)
    {
        var type = (Type)c.GetPrivateFieldValue("ClrType");
        var tableName = (string)c.GetPrivateFieldValue("EntitySetName");
        mapping[type] = tableName;
    }
    // store mapping whereever needed
}

主要思想是在base.OnModelCreating调用后获取配置对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2012-05-09
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多