我目前正在尝试通过设置的属性为我的表及其列添加前缀。我正在使用Entity Framework Core。我已经正确地为表名添加前缀,但我似乎无法弄清楚这些列。我有一种感觉,我需要使用反射。
我已经离开了我的(可能很差)尝试反思。有人有办法在实体中设置列的名称吗?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Debugger.Launch();
//Loop though each entity to set table names correctly
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
//Get the custom attributes of the entity
var attributes = entity.ClrType.GetCustomAttributes(true);
//Throw exception if there isn't any custom attribute applied to the class
if (attributes.Length == 0)
throw new ArgumentNullException(nameof(entity), "Entity is missing table prefix.");
//Get the table prefix
var prefix = attributes[0];
//Set the table name
entity.Relational().TableName = prefix + entity.Relational().TableName;
//Loop through all the columns and apply the prefix
foreach (var prop in entity.GetProperties())
{
var propInfo = entity.ClrType.GetProperty(prop.Name);
propInfo.SetValue(entity.ClrType, prefix + prop.Name, null);
}
}
}
它与您对表名所做的类似。只需使用Relational()和IMutableProperty
属性的ColumnName扩展方法:
foreach (var prop in entity.GetProperties())
{
prop.Relational().ColumnName = prefix + prop.Relational().ColumnName;
}