简体   繁体   中英

Automatically store pickled data, retrieve unpickled data with EF5

The title is awful, I know, so here's the long version:

I need to store variable data in a database column -- mostly key-value pairs, but both the number of items and the names of those items are completely unknown at run-time. My initial thinking is to "pickle" the data (a dictionary) into something like a JSON string, which can be stored in the database. When I retrieve the item, I would convert ("unpickle") the JSON string into a normal C# dictionary. Obviously, I don't want anyone directly interacting with the JSON string, though, so the actual property corresponding to the database column should be private, and I would have a public getter and setter that would not be mapped.

private string Data { get; set; }
public Dictionary<string, object> DataDictionary
{
    get
    {
        return Deserialize(Data);
    }
    set
    {
        Data = Serialize(value);
    } 
}

The problem of course is that EF will refuse to map the private Data property and actually want to map the public DataDictionary property, which shouldn't be mapped. There's ways around this, I believe, but the complexity that this starts generating makes me think I'm going down a rabbit hole I shouldn't. Is my thinking reasonable here, or should I go a different direction?

I suppose I could simply create a one-to-many relationship with a basic table that just consisted of key and value columns, but that feels hackneyed. However, perhaps, that actually is a better route to go given the inherent limitations of EF?

Have you tried using Complex Types ? You should be able to achieve your goal by creating a complex type of string on the EF Model.

Start by adding a complex type to the Model. On the complex type, add a scalar property of type string that will hold the data.

You can then create a property of this complex type on the entity that will hold the data.

The code generator should add a partial class that provides access to the properties for the complex type. Create a new partial class of the complex type and add in the serialisation/de-serialisation code as a property as in your question. You can then use this property to access the data.

The complex type in this example is essentially acting as a wrapper for a value that allows you to store the data value to storage.

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