如何在Entity Framework Core中获取映射实体的表名

And*_*Cui 30 entity-framework-core .net-core asp.net-core

在某些原因,我需要在EFCore中使用SQL,我将使用映射实体的表名.我怎么才能得到它?

Krz*_*cki 46

使用Microsoft.EntityFrameworkCore.Relational包:

var mapping = dbContext.Model.FindEntityType(typeof(YourEntity)).Relational();
var schema = mapping.Schema;
var tableName = mapping.TableName;
Run Code Online (Sandbox Code Playgroud)

这假定它dbContext是继承自的类的实例,DbContext并且您已在其中进行了YourEntity配置.

  • 此外,还有一个可用于“IEntityType”的扩展方法。所以 `entityType.GetTableName()` (2认同)
  • 有一个新的扩展方法,它提供以模式名称开头的表名称:“entityType.GetSchemaQualifiedTableName()”。手动创建查询可能很有用。 (2认同)

She*_*ari 5

您可以使用这个静态类

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

例如,我们有 Person 类,数据库中的实体名称是 People,我们可以从 person 类中获取人员。

var TblName= AttributeReader.GetTableName<YourModel>(YourContext);
Run Code Online (Sandbox Code Playgroud)