1
votes

I am trying to store an object as JSON. Then, convert it back from JSON string to an object with Entity Framework Core 3 using C#.

I have the following 2 model classes:

public class A
{    
    public int Id { get; set; }

    // more properties

    // I want to store the data as json.
    public CustomObject Object { get; set; }
}

public class CustomObject
{
    public int? Id { get; set; }
    public int[] ItemIds { get; set; }
    public string Value { get; set; }
}

Then in my DbContext I added the following

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<A>.Property(x => x.Object).HasConversion(
         v => JsonConvert.SerializeObject(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }),
         v => JsonConvert.DeserializeObject<T>(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
            );
}

However, when the app run I get the following error

System.InvalidOperationException: 'The property 'Object.ItemIds' could not be mapped, because it is of type 'int[]' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'

That error occurs when I try to set the entity in a generic class like this

Repository = context.Set<A>();

How can I correctly convert JSON string to an object and an object back to a JSON string with Entity Framework Core?

1
Can you include the statement that causes that exception to be thrown? - devNull
@devNull I updated the question to show where. It happenn when context.Set<A>() is called - John
You don't by chance have a DbSet<CustomObject> in your context do you? - Aluan Haddad
I don’t. I have DbSet<A> listed in the DbContext - John

1 Answers

0
votes

The issue is that EF is added the complex types by default "or something around these lines". To ignore it, I added the following and it worked

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Ignore<CustomObject>();
    // ...
}