В последнее время в EF core 7 возможен столбец json, и я ищу решение для абстрактного столбца json. В случае, если сохранить тип объекта в другом столбце, можно ли получить значение свойства, приведенное к производному классу?
Что-то в качестве примера ниже:
class MyEntity
{
public int Id { get; set; }
public int Title { get; set; }
public string ContentType { get; set; } // Store the type name as well
public Base Content { get; set; }
}
abstract class Base
{
public int Value1 { get; set; }
public int Value2 { get; set; }
}
class DerivedType1 : Base
{
public string Foo { get; set; }
}
class DerivedType2 : Base
{
public string Bar { get; set; }
}
После расследования больше. Я нашел одно решение, которое не идеально для меня. Я просто публикую его, и в случае, если нет другого решения, я отмечу его как ответ. Entity Framework также поддерживает JsonDocument для столбца Json, и мы можем использовать JsonDocument и использовать настраиваемое свойство для сериализации и десериализации объекта.
using System.Text.Json;
class MyEntity
{
public int Id { get; set; }
public int Title { get; set; }
public string ContentType { get; set; } // Store the type name as well
public JsonDocument Content { get; set; }
[NotMapped]
public Base CastedContent
{
get => (Base)Content.Deserialize(Type.GetType(ContentType));
set
{
Content = JsonSerializer.SerializeToDocument(value);
ContentType = value.GetType().FullName;
}
}
}