Ef code first: get entity table name without dataannotations

Is there a way to get table information defined using DbModelBuilder?

sort of:

entity.GetType().GetTableName()

Max

EDIT:

id how to implement the following

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

now I want to get the table name by type

var type = someEntity.getType();
var sql = "delete from " + Helper.GetTableName(type) + " where id in (...)"
+3
source share
1 answer

The only solution I can imagine is reflection. Here

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
}

The main idea is to get the configuration object after base.OnModelCreating is called.

+1
source

All Articles