2

We have a class that wraps a MathNet.Numerics matrix:

public class Matrix
{
    public MathNet.Numerics.LinearAlgebra.Matrix<double> _matrix { get; set; }

    public int? DatabaseId { get; set; }

    // ...
}

We need to store this Matrix in the database using Entity Framework. Entity Framework is presently ignoring this property. I'm using Fluent API mapping and currently have this set up:

modelBuilder.Entity<Matrix>()
       .HasKey(matrix => matrix.DatabaseId);

How can I use Entity Framework to persist my Math.Net Numerics Matrix wrapper in the database, including the _matrix property? What should the table structure be? (I'm using Npgsql so I have to build the tables myself.) Thanks in advance.

Scotty H
  • 6,432
  • 6
  • 41
  • 94
  • Do you know whether this is always a dense matrix internally, or can it also be e.g. sparse or diagonal? – Christoph Rüegg Sep 23 '15 at 15:37
  • I would prepare a serialized property of `byte[]` (representing `Matrix`), that means you save that as binary in database. You need another not-mapped property (or even a helper method) to parse/deserialize `byte[]` into `Matrix`. However that deserialized property or helper method cannot be used in the Linq-To-Entity query. – Hopeless Sep 23 '15 at 15:53

1 Answers1

1

You'll likely need some kind of surrogate to do this in a sensible way, so it actually writes a string or a binary blob to the database (instead of trying to decompose the type and its members).

For example, you could serialize it into MatrixMarket format (string, optionally compressed to a binary stream; very simple but you could loose some precision), or MATLAB (binary stream; currently only the old Level-5 format supported).

Christoph Rüegg
  • 4,626
  • 1
  • 20
  • 34