什麼是中繼資料?
「百科」中繼資料被定義為:描述資料的資料,對資料及資訊資源的描述性資訊。
「知乎」什麼是中繼資料?為何需要中繼資料?
EF Core 底層中繼資料資訊
Microsoft.EntityFrameworkCore.Metadata Namespace
若要擷取上述底層中繼資料,可使用 IModel 接口中提供的兩個最核心的方法。
IEnumerable<IEntityType> GetEntityTypes();
IEntityType FindEntityType(string name);
通過兩種方式擷取 IModel 接口:DbContext.Model 或者 ModelBuilder.Model 。
寫幾個常用的示例
查詢表的中繼資料
var entityType = _context.Model.FindEntityType(typeof(Blog).FullName);
string tableName = entityType.Relational().TableName;
動态擷取屬性中繼資料
var entityType = _context.Model.FindEntityType(typeof(Blog).FullName);
IEnumerable<IProperty> properties = entityType.GetProperties();
foreach (var property in properties)
{
Console.WriteLine(property.Name);
}
動态擷取列中繼資料
var entityType = _context.Model.FindEntityType(typeof(Blog).FullName);
IProperty property = entityType.FindProperty(nameof(Blog.Url));
string columnName = property.Relational().ColumnName;
Lambda 表達式擴充方法
public static class DbContextMetadataExtensions
{
public static Iproperty FindProperty<TEntity, TProperty>(this DbContext
dbContext, Expression<Func<TEntity, TProperty>> expression)
{
var memberExpression = (MemberExpression)expression.Body;
PropertyInfo propertyInfo =
typeof(TEntity).GetProperty(memberExpression.Member.Name);
var entityType =
dbContext.Model.FindEntityType(typeof(TEntity).FullName);
IProperty property = entityType.FindProperty(propertyInfo.Name);
return property;
}
}
IProperty property = _context.GetProperties<Blog, string>(m => m.Url);
string columnType = property.Relational().ColumnType;