EF Core: Find a database field name for a provided entity property name


Overview

This DbContext extension method will allow you to retrieve the database field name of a specific entities property (e.g. you could find a database field name of first_name from the Person.FirstName property.

C#

/// <summary>
/// Finds the database field name for a property of T.  This can be called by passing
/// the string name, or by passing the string name as discerned from the actual property
/// with nameof (which is the preferred version).  e.g. nameof(CodeTable.Code).  Calling nameof
/// in that manner will allow you to reference the property even if it's not an instantiated
/// object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="db"></param>
/// <param name="propertyName"></param>
public static string? DbFieldName<T>(this DbContext db, string propertyName)
{
	// Get the entity type for the class
	var entityType = db.Model.FindEntityType(typeof(T));

	// Get the property by the name of the property passed in.  This is the
	// .NET property name.
	var codeProperty = entityType?.FindProperty(propertyName);

	// Get the database field name property we located.
	return codeProperty?.GetColumnName();
}

Usage

The preferred usage if possible for your use case utilizes nameof which will help protect against issues where the property name might change.

string dbFieldName = dbContext.DbFieldName<Person>(nameof(Person.FirstName))
string dbFieldName = dbContext.DbFieldName<Person>("FirstName")