Search code examples
entity-frameworkef-code-firstfluent-interface

How to find which Table is mapped by fluent API?


I need to find which table is mapped to an EntityTypeConfiguration class. For example:

  public class PersonMap : EntityTypeConfiguration<Person>
    {
        public PersonMap()
        {
    ...
            this.ToTable("Persons");
    ....

        }
    }

I need something like reverse mapping:

var map=new PersonMap(); 
string table =map.GetMappedTableName();

How can I achieve this?


Solution

  • Add the field to PersonMap:

    public class PersonMap : EntityTypeConfiguration<Person>
    {
        public string TableName { get { return "Persons"; } }
        public PersonMap()
        {
            ...
            this.ToTable(TableName);
            ...
        }
    }
    

    Access it like so:

    var map = new PersonMap(); 
    string table = map.TableName;
    

    If you may not know the type of map, use an interface:

    public interface IMap
    {
        string TableName { get; }
    }
    public class PersonMap : EntityTypeConfiguration<Person>, IMap
    {
        public string TableName { get { return "Persons"; } }
        public PersonMap()
        {
            ...
            this.ToTable(TableName);
            ...
        }
    }
    

    Access like so:

    IMap map = new PersonMap(); 
    string table = map.TableName;