Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 with an Immutable Class

I have a Point class:

// My immutable Point class
public class Point
{
    private readonly Distance _x;
    private readonly Distance _y;
    private readonly Distance _z;

    public Distance X
    {
        get { return _x; }
    }

    public Distance Y
    {
        get { return _x; }
    }

    public Distance Z
    {
        get { return _x; }
    }

    // Ok, so this isn't immutable... but it's purely for EF
    public int DatabaseId { get; set; }

    public Point(Distance x, Distance y, Distance z)
    {
        _x = x;
        _y = y;
        _z = z;
    }
}

(Distance is a custom class that stores a unit and a value.)

That's great. We love immutability. But Entity Framework won't recognize that I need to put X, Y, and Z in the database because they don't have setters. And they shouldn't, because this is an immutable class. There shouldn't even be a private set.

I have this code building my model:

    modelBuilder.Entity<Point>()
        .HasKey(point => point.DatabaseId);

Is there any way to preserve the true immutability of this class but also make it so that EF6 can access and store these values?

like image 427
Scotty H Avatar asked Oct 31 '22 20:10

Scotty H


1 Answers

In a similar situation, I had to create a private parameterless constructor that EntityFramework can use and made the Id as private set. This worked for me fine and it's the best I could do in the time I had in keeping the class immutable.

So in your case, the above class could be updated and simplified as follows:

public class Point
{
    public Distance X { get; private set; }
    public Distance Y { get; private set; }
    public Distance Z { get; private set; }
    public int DatabaseId { get; private set; } // DatabaseId can't be set publicly

    private Point() { } // Private Parameterless Constructor for EntityFramework

    public Point(Distance x, Distance y, Distance z)
    {
        X = x;
        Y = y;
        Z = z;
    }
}

Hope this helps!

like image 50
hem Avatar answered Nov 09 '22 08:11

hem