0

I have such EntityTypeConfiguration class.

public class DummyTypeConfiguration : IEntityTypeConfiguration<DummyType>
{
  public void Configure(EntityTypeBuilder<DummyType> builder)
  {
      builder.HasNoKey();
      builder.Property(p => p.SecretId).HasColumnName("secretID");
      ...
  }
}

I want to retrieve the column name: "secretID" by using the property DummyType.SecretId as such:

var columnName = ...(DummyType.SecretId);

2 Answers 2

2

EF Core 6: That can be done using the code below:

var entityType = _dataContext.Model.FindEntityType(typeof(DummyType));
var property = entityType?.GetProperty(nameof(DummyType.SecretId));
var columnName = property?.GetColumnName();

The _dataContext variable represents object instance of DbContext class.

Sign up to request clarification or add additional context in comments.

Comments

0

When using TPH for storing entities class hierararchy, there can be case when some derived entities have the same property name. Column names in the database table then needs to be different for the two entities.

For example:

BaseClass class

  • DerivedClassA
    • string Name
  • DerivedClassB
    • string Name

Table BaseClass

  • column Name
  • column DerivedClassB_Name

This behavior is mentioned here: https://github.com/dotnet/efcore/issues/11046

GetColumnName() method returns "Name" for both cases. To get the real column name, method GetColumnName must be called with parameter StoreObjectIdentifier.Table(tableName). This returns "Name" for DerivedClassA entity and "DerivedClassB_Name" for DerivedClassB entity.

So, te code would be:

var entityType = _dataContext.Model.FindEntityType(typeof(DummyType));
string tableName = entityType.GetTableName();
var property = entityType?.GetProperty(nameof(DummyType.SecretId));
var columnName = property?.GetColumnName(StoreObjectIdentifier.Table(tableName));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.