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;
}
}
例如,我们有 Person 类,数据库中的实体名称是 People,我们可以从 Person 类中获取人。
var TblName= AttributeReader.GetTableName<YourModel>(YourContext);
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");
}
接下来是西蒙的回答。在 EFCoreVersion5x 中,可以使用 Microsoft 扩展方法。创建了一个 DbContext助手扩展方法:
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();
}
}
/// <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();
}
用法如下:
var context = new SystemContext();
var name = context.SystemTable.GetTableSchemaName();