Search code examples
c#jsonentity-framework-coreef-core-7.0

How to use OwnsOne and OwnsMany function in EF Core 7 to store an array of string json in a column?


I want to achieve something like this:

name tags
first ["tag#1", "tag2"]
second ["tag#1", "tag2", "tag3"]

This is the entity type, Category:

public class Category
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<string> Tags { get; set; }
}

And this is the configuration:

builder.OwnsMany(category => category.Data, b =>
     {
         b.ToJson();
     });
builder.Property(x => x.Name).HasMaxLength(450);

But I get the following error:

No suitable constructor was found for entity type 'string'. The following constructors had parameters that could not be bound to properties of the entity type


Solution

  • You can use custom converter to convert array primitive data type. Here uses Newtonsoft.Json. You can use System.Text.Json instead.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<YourEntity>().Property(s => s.PrimitiveArray).HasConversion<JsonPrimitiveTypeConverter>();
    }
    
    public class JsonPrimitiveTypeConverter : ValueConverter<List<string>, string>
    {
        public JsonPrimitiveTypeConverter() : base(
                d => d == null
                ? default
                : JsonConvert.SerializeObject(d),
            d => d == null
                ? default
                : JsonConvert.DeserializeObject<List<string>>(d))
        {
        }
    }