How to store double[] array to database with Entity Framework Code-First approach

jonas picture jonas · Mar 5, 2013 · Viewed 35k times · Source

How can I store an array of doubles to database using Entity Framework Code-First with no impact on the existing code and architecture design?

I've looked at Data Annotation and Fluent API, I've also considered converting the double array to a string of bytes and store that byte to the database in it own column.

I cannot access the public double[] Data { get; set; } property with Fluent API, the error message I then get is:

The type double[] must be a non-nullable value type in order to use it as parameter 'T'.

The class where Data is stored is successfully stored in the database, and the relationships to this class. I'm only missing the Data column.

Answer

Joffrey Kern picture Joffrey Kern · Mar 5, 2013

You can do a thing like this :

    [NotMapped]
    public double[] Data
    {
        get
        {
            string[] tab = this.InternalData.Split(',');
            return new double[] { double.Parse(tab[0]), double.Parse(tab[1]) };
        }
        set
        {
            this.InternalData = string.Format("{0},{1}", value[0], value[1]);
        }
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    public string InternalData { get; set; }