Set column names during OnModelCreating

c# entity-framework-core



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?


protected override void OnModelCreating(ModelBuilder modelBuilder)
    //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);
4/1/2019 10:36:18 AM

Accepted Answer

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;
4/1/2019 10:37:33 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow