问题
我目前正在尝试通过设置的属性为我的表及其列添加前缀。我正在使用 Entity Framework 核心。我已经正确地为表名添加了前缀,但我似乎无法弄清楚列的前缀。我有一种感觉,我需要使用反射。
我已经留下了我的(可能很糟糕的)反射(reflection)尝试。有人有办法在实体中设置列的名称吗?
代码
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;
}
关于c# - 在 OnModelCreating 期间设置列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55452732/