How to get Table Name of mapped entity in Entity Framework 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");
}
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();
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);