Home > Back-end >  Using abstract json column in Entity Framework
Using abstract json column in Entity Framework

Time:11-23

Recently in EF core 7 the json column is possible and I am looking for a solution to have a abstract json column. In case, if store the type of the object in another column, is it possible to get the property value casted to derived class?

Something as example below:

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; }
}

CodePudding user response:

After investigate more. I found one solution which is not ideal for myself. I just post it and in case if there is no other solution I will mark it as answer. Entity Framework support JsonDocument for Json column as well and we can use JsonDocument and use custom property to serialize and deserialize the object.

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;
        }
    }
}


  • Related