问题
Issue
I am currently trying to prefix my tables and their columns via an attribute that is set. I am using Entity Framework Core. I've gotten it right to prefix the table name but I cannot seem to figure it out for the columns. I have a feeling I will need to use reflection.
I have left my (probably poor) attempt at reflection in. Does someone have a way of setting the name of a column in an entity?
Code
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);
}
}
}
回答1:
It's similar to what you did with the table name. Just use the Relational() extension method of IMutableProperty
and ColumnName property:
foreach (var prop in entity.GetProperties())
{
prop.Relational().ColumnName = prefix + prop.Relational().ColumnName;
}
来源:https://stackoverflow.com/questions/55452732/set-column-names-during-onmodelcreating