I'm storing transactions in an SQL database using EF code first and MVC6 I need to reverse the sign of the value based on the type of transaction. I want to do this at a central point so I don't have to make multiple changes throughout the app. i.e. on model creation or on the entity. Something like:
public class Transactions : EntityBase
{
public TransactionType Type { get; set; }
public decimal Amount
{
get
{
if (Type == Type.Refund && Amount > 0)
return Amount * -1;
else
return Amount;
}
set { Amount = value; }
}
}
We could also store the value as a negative. Any suggestion on how best to achieve this?
You could go ahead and create an unmapped property and one that is filled by EF.
public class Transactions : EntityBase
{
public TransactionType Type { get; set; }
public RawAmount { get; set; }
[NotMapped]
public decimal Amount
{
get
{
if (Type == Type.Refund && RawAmount > 0)
return RawAmount * -1;
else
return RawAmount;
}
set
{
Type = value > 0 ? Type.Expense : Type.Refund;
Amount = Math.Abs(value);
}
}
}
If you are using fluent configurations in EF you could even make the RawAmount property protected, so it is not used by mistake.