MCV6 EF根据事务类型更改小数的符号



我首先使用EF代码将事务存储在SQL数据库中,MVC6我需要根据事务类型反转值的符号。我想在一个中心点做这件事,这样我就不必在整个应用程序中进行多次更改。即在模型创建上或在实体上。类似于:

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; }
}
}

我们也可以将该值存储为负数。关于如何最好地实现这一点,有什么建议吗?

您可以继续创建一个未映射的属性和一个由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); 
}
}
}

如果您在EF中使用fluent配置,您甚至可以保护RawAmount属性,这样就不会错误使用它。

最新更新