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配置.
您可以使用这个静态类
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)
| 归档时间: |
|
| 查看次数: |
9647 次 |
| 最近记录: |