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

.net c# ef-code-first entity-framework fluent-interface

Question

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.

1
25
3/5/2013 10:03:21 AM

Accepted Answer

Thank you all for your inputs, due to your help I was able to track down the best way to solve this. Which is:

 public string InternalData { get; set; }
 public double[] Data
 {
    get
    {
        return Array.ConvertAll(InternalData.Split(';'), Double.Parse);                
    }
    set
    {
        _data = value;
        InternalData = String.Join(";", _data.Select(p => p.ToString()).ToArray());
    }
 }

Thanks to these stackoverflow posts: String to Doubles array and Array of Doubles to a String

26
5/23/2017 11:46:27 AM

Popular Answer

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; }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow