我目前正在尝试通过设置的属性为表及其列添加前缀。我正在使用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);
}
}
}
答案 0 :(得分:3)
它类似于您对表名所做的操作。只需使用IMutableProperty
和Relational()属性的ColumnName扩展方法:
foreach (var prop in entity.GetProperties())
{
prop.Relational().ColumnName = prefix + prop.Relational().ColumnName;
}