I'm doing a migration and I don't see the property from the inheritor class. I have next model. In class SomeClass i have virtual property which is correctly displayed, but when inheriting in the class, nothing is show
public class School
{
[Key]
public long Id { get; init; }
[Column(TypeName = "jsonb")]
public SomeClass Parameter1 { get; set; }
}
public class SomeClass
{
public virtual ParameterTypes Type { get; }
}
public enum ParameterTypes
{
None,
Value
}
public class DerivedClass : SomeClass
{
public override ParameterTypes Type => ParameterTypes.Value;
public string Value { get; set; }
}
and i am add configure this model
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<School>(
builder =>
{
builder.HasKey(h => h.Id);
builder.Property(h => h.Parameter1).HasJsonConversion();
});
}
public static PropertyBuilder<T> HasJsonConversion<T>(this PropertyBuilder<T> propertyBuilder)
where T : class, new()
{
var converter = new ValueConverter<T, string>(
v => JsonSerializer.Serialize(v, null),
v => JsonSerializer.Deserialize<T>(v, null) ?? new T());
var comparer = new ValueComparer<T>(
(l, r) => JsonSerializer.Serialize(l, null) == JsonSerializer.Serialize(r, null),
v => v == null ? 0 : JsonSerializer.Serialize(v, null).GetHashCode(),
v => JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(v, null), null)
);
propertyBuilder.HasConversion(converter);
propertyBuilder.Metadata.SetValueConverter(converter);
propertyBuilder.Metadata.SetValueComparer(comparer);
propertyBuilder.HasColumnType("jsonb");
return propertyBuilder;
}
when I do a migration, I see enum as a string (right), but I don’t see the property DerivedClass.Value
maybe the problem is in the HasJsonConversion method?
how to get property from inherited class?
CodePudding user response:
var converter = new ValueConverter<T, string>(
v => JsonSerializer.Serialize(v, **v.GetType()**, jsonSerializerOptions),
v => JsonSerializer.Deserialize<T>(v, jsonSerializerOptions));