I would like to save some work by avoiding having 2 sets of entities in my code. As of now I have the first set which is just a bunch dummy surrogate entities for EF with default constructors and settable properties, so that it can map to them. The other one is a set of real entities that I use in my business code. The real ones are immutable and fully initialized at the time of being created by using initializing constructors.
Is there a way to avoid having surrogates and map straight to the real entities by using some sort of factories in EF that are able to deal with initializing constructors without using settable properies?
It isn't possible, EF require parameterless constructor and it must be able to set properties.
For better encapsulation you can make property setters protected
. EF will still be able to set property values (via generated proxy) but from the outer point of view it will look immutable.
Can't add comment, so. Now it's possible, because EF now can map private properties. And in 6.1.3 doing it by default(not sure about previous releases). Example 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;
}
}
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