C#C
C#3y ago
Strawb

❔ Generic entity type in EF Core

Heya everyone! GuraWave2
What's the recommended way to work with entities that have a property with a generic type on them? e.g:
internal sealed class MetricsEntity<TMetric> : Entity
    where TMetric : class
{
    public TMetric Data { get; set; } = default!;
}

I'd like to serialize and deserialize the data as JSON with a config that looks something like this: (I don't need to query the JSON data in the db)
internal sealed class MetricEntityConfiguration<TMetric> : IEntityTypeConfiguration<MetricsEntity<TMetric>>
    where TMetric : class
{
    public void Configure(EntityTypeBuilder<MetricsEntity<TMetric>> builder)
    {
        builder.ToTable(MetricTableNames.Metric, MetricTableNames.SchemaName);
        builder.HasKey(x => x.Id);
        builder.OwnsOne(x => x.Data, b => b.ToJson());
    }
}

Sadly though, that doesn't seem to work as I get an error saying: The entity type 'MetricsEntity<TestMetricData>' was not found. (I do have the model builder configured to use all type builders of the assembly)

What's the preferred way to implement this? confuseddog
  • Do I dynamically add a type configuration for all constructed generic types using reflection?
  • Do I change the property to be a string and serialize / deserialize it myself?
  • Do I do something entirely different? :0
Was this page helpful?