Is there a way to map to immutable objects in an entity structure?

I would like to save some work by avoiding having two sets of objects in my code. At the moment, I have the first set, which is just a bunch of surrogate surrogate objects for EF with standard constructors and custom properties so that it can display them. Another is a set of real objects that I use in my business code. The real ones are immutable and fully initialized at creation time using initialization constructors.

Is there a way to avoid surrogates and map directly to real objects using some factories in EF that can deal with initializing constructors without using custom properties?

+7
immutability c # orm entity-framework
source share
2 answers

This is not possible, EF requires a constructor without parameters and it must be able to set properties.

For better encapsulation, you can make protected property settings. EF will still be able to set property values ​​(via the generated proxy), but from an external point of view it will look unchanged.

+6
source share

Unable to add a comment. This is now possible because EF can now display private properties. And in 6.1.3 it does this by default (not sure about previous releases). An example is below.

 class Program { static void Main(string[] args) { using (var context = new MyContext()) { context.MyImmutableClassObjects.Add(new MyImmutableClass(10)); context.MyImmutableClassObjects.Add(new MyImmutableClass(20)); context.SaveChanges(); var myImmutableClassObjects = context.MyImmutableClassObjects.ToList(); foreach (var item in myImmutableClassObjects) { Console.WriteLine(item.MyImmutableProperty); } } Console.ReadKey(); } } public class MyContext : DbContext { public DbSet<MyImmutableClass> MyImmutableClassObjects { get; set; } } public class MyImmutableClass { [Key] public int Key { get; private set; } public int MyImmutableProperty { get; private set; } private MyImmutableClass() { } public MyImmutableClass(int myImmutableProperty) { MyImmutableProperty = myImmutableProperty; } } 
+3
source share

All Articles