简体   繁体   中英

.net core Serialize and deserialize Generic type

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>

您可以使用值转换将属性存储为 JSON 字符串(更好)或字节 [](脆弱、非人类可读、无法在数据库中使用)。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM