How to get Table Name of mapped entity in Entity Framework Core

asp.net Core.Net CoreEntity Framework-Core

asp.net Core Problem Overview


In some reason, I need to use SQL in EFCore, and I will use table name of mapped entity. How can I get it?

asp.net Core Solutions


Solution 1 - asp.net Core

Using the Microsoft.EntityFrameworkCore.Relational package in 2.X:

var mapping = dbContext.Model.FindEntityType(typeof(YourEntity)).Relational();
var schema = mapping.Schema;
var tableName = mapping.TableName;

This assumes that dbContext is a instance of class that inherits from DbContext and that you have YourEntity configured there.

Note that in EF Core 3.X, [.Relational() provider extensions have been replaced] (https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#provider) with getters and so you can now access the schema as follows:

var entityType = dbContext.Model.FindEntityType(typeof(YourEntity));
var schema = entityType.GetSchema();
var tableName = entityType.GetTableName();

Solution 2 - asp.net Core

You can Use this static class

public static class AttributeReader
{
    //Get DB Table Name
    public static string GetTableName<T>(DbContext context) where T : class
    {
        // We need dbcontext to access the models
        var models = context.Model;

        // Get all the entity types information
        var entityTypes = models.GetEntityTypes();

        // T is Name of class
        var entityTypeOfT = entityTypes.First(t => t.ClrType == typeof(T));

        var tableNameAnnotation = entityTypeOfT.GetAnnotation("Relational:TableName");
        var TableName = tableNameAnnotation.Value.ToString();
        return TableName;
    }

}

For example, we have Person class that entity name in database is People, we can get people from person class.

var TblName= AttributeReader.GetTableName<YourModel>(YourContext);

Solution 3 - asp.net Core

EF Core 5 version

EF Core 5 "now allows an entity type to be mapped to both a table and a view simultaneously".

I don't fully understand this, but it adds complications to finding table names.

For my use case I actually wanted the name of a view, so by checking for TableName and ViewName I could throw an error if the entity supplied was for the wrong type.

var entityType = typeof(Customer);
var modelEntityType = context.Model.FindEntityType(entityType);

string tableName = modelEntityType.GetSchemaQualifiedTableName();
string viewName = modelEntityType.GetSchemaQualifiedViewName();

if (tableName != null) 
{
   throw new Exception("The Entity " + entityName + " represents a table and not a view");
}

Solution 4 - asp.net Core

Following on from Simon's answer. In EF Core Version 5x, it is possible to use Microsoft extension methods. Created a DbContext helper extension method:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

public static class EfCoreExtensions
{
   public static string GetSchemaQualifiedTableName(this DbContext context, Type entityType)
   {
      IEntityType et = context.Model.FindEntityType(entityType);
      //what to do here, entity could be both view and table!?
      //string viewName = et.GetSchemaQualifiedViewName();
      return et.GetSchemaQualifiedTableName();
   }
}

Example of use like this:

  string tableName = _dbContext.GetSchemaQualifiedTableName(typeof(SomeEntity));

The MS extension methods are housed in the class:

Microsoft.EntityFrameworkCore.RelationalEntityTypeExtensions

Referenced using Nuget

<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.4" />

Solution 5 - asp.net Core

DbSet Extension Method to Get Schema Name

Following on from Rax's extension method, you can write an extension method straight off of a DBSet as per below:

    /// <summary>
    /// Gets the Schema Table name for the DbSet.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dbSet"></param>
    /// <returns></returns>
    public static string GetTableSchemaName<T>(this DbSet<T> dbSet) where T : class
    {
        var context = dbSet.GetService<ICurrentDbContext>().Context;
        var entityType = typeof(T);
        var m = context.Model.FindEntityType(entityType);

        return m.GetSchemaQualifiedTableName();
    }

Used like this:

var context = new SystemContext();
var name = context.SystemTable.GetTableSchemaName();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew CuiView Question on Stackoverflow
Solution 1 - asp.net CoreKrzysztof BranickiView Answer on Stackoverflow
Solution 2 - asp.net CoreShervin IvariView Answer on Stackoverflow
Solution 3 - asp.net CoreSimon_WeaverView Answer on Stackoverflow
Solution 4 - asp.net CoreRaxView Answer on Stackoverflow
Solution 5 - asp.net CorePaulView Answer on Stackoverflow