'GetColumnName() in EF Core 6 returns property name not mapped column name

I'm using EF Core 6 (6.0.2) with SQL Server 2019 with the following entity:

public partial class MyEntity
{
        [Column("External_ExternalId")]
        public Guid? ExternalId { get; set; }
}

I'm trying to get the mapped column name (External_ExternalId) for the ExternalId property with the following code:

var entityType = dbContext.Model.FindEntityType(typeof(MyEntity));
var property = entityType.GetProperties().Single(property => property.Name.Equals("ExternalId", StringComparison.OrdinalIgnoreCase));
var columnName = property.GetColumnName(StoreObjectIdentifier.Create(property.DeclaringEntityType, StoreObjectType.Table).GetValueOrDefault());

columnName is ExternalId instead of External_ExternalId. How can I get the actual name of the table's column? I tried GetColumnBaseName() but got the same result. Same if I configure the mapping with the fluent API.



Solution 1:[1]

Because the column name is defined using a [Column(...)] attribute, you can get the desired outcome by looking for ColumnAttribute objects that are attached to the properties of the class, as follows:

public static void PrintValueOfColumnAttribute()
{
    PropertyInfo[] props = typeof(MyEntity).GetProperties();
    foreach (PropertyInfo prop in props)
    {
        foreach (var attr in prop.GetCustomAttributes(true))
        {
            if (attr is ColumnAttribute columnAttr)
            {
                Console.WriteLine(prop.Name + " -> " + columnAttr.Name);
            }
        }
    }
}

Result:

ExternalId -> External_ExternalId

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter B