Home > database >  .net core Serialize and deserialize Generic type
.net core Serialize and deserialize Generic type

Time:10-18

class Order<T>
{
  public Int orderId { get; set; }
  
  public IDictionary<string, T> Details { get; set; }

}

I want to store this in sql db Details as byte array using entity framework

Is it possible to store and retrieve it and reconstruct back to Order object?

Any suggestions on how to do it?

Other option is, I can change to byte[] and store in db, but not sure how to deserialize byte array back to IDictionary<string, T>

CodePudding user response:

You can use a Value Conversion to store the property as a JSON string (better) or a byte[] (brittle, not-human-readable, not usable in the database).

CodePudding user response:

To serialise & deserialise your object check out the answers to Convert any object to a byte[]

Once you have the byte array you can just read and write it to the database using a blob storage column.

However, doing this is extremely dangerous. Any change in your database schema will cause breaking changes. This will require you to read each row into an external program and convert it to the new format as you won't be able to perform the migration using a SQL script.

Likewise storing it as JSON or XML data is also ill advised for the same reasons. Hell, they might even be worse depending on your data (never seen a JSON document store an image well).

If you are able to spend the time, create a mapping table and construct the dictionary yourself. I'm unsure what the T is, but if it's another database record then you're set. Otherwise maybe the binary serialisation is the way to go.

  • Related