MCV6 EF 根据交易类型更改小数点符号
MCV6 EF Changing the sign of a decimal based on transaction type
我首先使用 EF 代码和 MVC6 将交易存储在 SQL 数据库中,我需要根据交易类型反转值的符号。我想在一个中心点执行此操作,这样我就不必在整个应用程序中进行多次更改。即在模型创建或实体上。类似于:
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 中使用流畅的配置,您甚至可以使 RawAmount 属性 受到保护,因此不会被错误使用。
我首先使用 EF 代码和 MVC6 将交易存储在 SQL 数据库中,我需要根据交易类型反转值的符号。我想在一个中心点执行此操作,这样我就不必在整个应用程序中进行多次更改。即在模型创建或实体上。类似于:
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 中使用流畅的配置,您甚至可以使 RawAmount 属性 受到保护,因此不会被错误使用。