简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM