Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 787
jonas Avatar asked Mar 05 '13 10:03

jonas


People also ask

Which is better code first or database first in Entity Framework?

3)Database Version Control Versioning databases is hard, but with code first and code first migrations, it's much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database.

How does Entity Framework handle lists?

If you have a list, it has to point to some entity. For EF to store the list, it needs a second table. In the second table it will put everything from your list, and use a foreign key to point back to your Test entity. So make a new entity with Id property and MyString property, then make a list of that.


2 Answers

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; } 
like image 69
Joffrey Kern Avatar answered Sep 21 '22 12:09

Joffrey Kern


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

like image 38
jonas Avatar answered Sep 23 '22 12:09

jonas