I am using EF Code First and I had a model like below.
public class Account
{
[Required]
public string AccountNo { get; set; }
[Required]
public decimal Balance { get; set; }
}
I used a Service class to withdraw and deposit amount to Account. Then I came across this and realised that Account is Anemic. So I happily added Withdraw and Deposit methods to Account.
public class Account
{
[Required]
public string AccountNo { get; set; }
[Required]
public decimal Balance { get; set; }
public void Withdraw(decimal amount)
{
// TODO: Check if enough balance is available
Balance -= amount;
}
public void Deposit(decimal amount)
{
Balance += amount;
}
}
I was very happy with this until I realised that this does not implement encapsulation correctly. You should not be able to modify the Balance directly - you should use Withdraw and Deposit methods. But in my solution you can modify the Balance directly.
But I cannot make Balance a readonly property as I am using EF code first approach and readonly properties won't result in the column being created in the database table.
I thought of leaving Account as anemic and create a higher level Account class which implements encapsulation and Withdraw/Deposit methods. But in that case the higher level class would not have validation data annotations and I won't get the free functionality provided by the framework.
What is the solution?
private
orpublic
. So if you are making something public just because you think entity framework won't be able to use it otherwise - don't.