ef code first: get entity table name without dataannotations

梦想的初衷 提交于 2019-12-18 06:57:30

问题


Is there a way to get table info defined with DbModelBuilder?

something like:

entity.GetType().GetTableName()

Max

EDIT:

id like to implement following

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

now i'd like to get table name by type

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

回答1:


Only solution i can imagine is reflection. Here it is

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
}

Main idea is to get configuration object after base.OnModelCreating has called.



来源:https://stackoverflow.com/questions/7008212/ef-code-first-get-entity-table-name-without-dataannotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!