Home > front end >  Problem with serialize and deserialize an entity when write or read using EF Core
Problem with serialize and deserialize an entity when write or read using EF Core

Time:06-02

I have a customer entity and it has a picture entity with the following properties:

public class Customer
{
    public Int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public Pictures Pictures { get; set; }
}

public class pictures
{
    public Guid? picture1 { get; set; }
    public Guid? picture2 { get; set; }
}

I am going to save it in database as a json, so I have serialized and deserialized it like this:

public class CustomerEntityTypeConfiguration : IEntityTypeConfiguration<Customer>
{
        public void Configure(EntityTypeBuilder<Customer> builder)
        {
            builder.ToTable("Customers");

            builder.HasKey(o => o.Id);

            builder.Property(o => o.Picures).HasConversion(
               s => JsonConvert.SerializeObject(s, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }),
               s => JsonConvert.DeserializeObject<Pictures>(s, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
            );
        }
}

This way, when I did not add any picture to pictures entity it shows me null for the field of pictures in the table, but I think it would be a json like this:

{
    picture1:"",
    picture2:""
}

I am going to save pictures as json but I think my entity did not serialize correctly because pictures field is null in the database and when I add a guid to each of its properties in the code as the following

customer.pictures.picture1 = pictureGuid;

I get an exception:

NullReferenceException: Object reference not set to an instance of an object

CodePudding user response:

When you did this: customer.pictures.picture1 = pictureGuid; your pictures object in the Customer is null because you didn't initialize it anywhere.

You can change your Customer class to this:

public class Customer
{
    public Int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public Pictures Pictures { get; set; } = new Pictures();
}

But I would rather think about the code logic in your place. Like, when you do customer.pictures.picture1 = pictureGuid why you pictures object is not initialized? Is it the first time accessing it? If so, then you should maybe first do: customer.pictures = new Pictures() and then assign value to it. It depends on a use case...

NullValueHandling.Ignore will just omit null properties of an object. It won't work when the whole object is null. So you need to have Pirtures object initialized at least.

You can check example for NullValueHandling options here: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

  • Related