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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With