Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to map to immutable entities in entity framework?

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?

like image 576
Trident D'Gao Avatar asked Oct 10 '13 14:10

Trident D'Gao


2 Answers

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.

like image 71
Lukas Kabrt Avatar answered Sep 27 '22 21:09

Lukas Kabrt


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;
    }
}
like image 26
Valeriy Y. Avatar answered Sep 27 '22 21:09

Valeriy Y.