5

What am trying to achieve is to create a class as shown below.

public class Purse
{
    public decimal AvaliableBalance { get; protected set; }        
    public decimal PendingBalance { get; protected set; }
    public decimal TotalBalance { get; protected set; }
}

But am wondering if entity framework will be able to populate this class. If so, how?

Basically what am trying to accomplish is to restrict writing directly to these properties on the code side but i want Entity framework to be able to write to this properties.I want to expose the setter of these properties through a method whose sole purpose is to write values to it (ie: after some processing of course).

Cizaphil
  • 490
  • 1
  • 6
  • 23

1 Answers1

5

Your approach will work. I have used this pattern heavily. Entity Framework uses reflection to materialize your data into objects. Since reflection will work happily even if your members are private, the pattern works well.

CShark
  • 2,183
  • 1
  • 24
  • 42
Nick Strupat
  • 4,928
  • 4
  • 44
  • 56
  • I see now, so its reflection. Thanks – Cizaphil Feb 02 '15 at 23:35
  • 2
    This answer is broadly correct but you can use also private properties - see http://www.dotnetjalps.com/2015/04/entity-framework-private-setters-constructors.html. As reflection can allow access to private properties if appropriately configured this makes sense. It's also possible to have constructors with parameters for use in the code and a private parameter free constructor (a parameter free constructor is required by Entity Framework) purely for Entity Framework use. – pwdst Sep 02 '16 at 11:24
  • http://thedatafarm.com/data-access/entity-framework-private-constructors-and-private-setters/ is also relevent – pwdst Sep 02 '16 at 11:28
  • With EF6 or higher (not sure about earlier versions), you are able to user private setters as well. Please refer to this answer https://stackoverflow.com/questions/26768695/can-private-setters-be-used-in-an-entity-model – CShark Aug 16 '17 at 08:51