ef code first: get entity table name without dataannotations

后端 未结 1 495
礼貌的吻别
礼貌的吻别 2020-12-20 00:13

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

something like:

entity.GetType().GetTableName()

Max

EDIT:

相关标签:
1条回答
  • 2020-12-20 00:43

    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.

    0 讨论(0)
提交回复
热议问题