问题
I am working with an existing [poorly designed] database which stores a dollar amount as an integer (ie. $10.99 == 1099) in the database. I want my entity class to treat this value as a decimal so that consuming code doesn't have to do the translation.
Is there a way to convert the value to and from integer to decimal and then back using Data Annotations or Fluent configuration?
In the meantime I am using a hack which essentially "wraps" the integer property with a decimal property that handles the translation.
[Column("intTotal")]
public virtual int TotalAsInt { get; set; }
[NotMapped]
public virtual decimal Total
{
get { return (decimal) TotalAsInt/100; }
set { TotalAsInt = (int)(value*100); }
}
回答1:
Is there a way to convert the value to and from integer to decimal and then back using Data Annotations or Fluent configuration?
Not as far as I know. Your solution looks good.
You could hide TotalAsInt
by making it a private
property, but then you couldn't use it in IQueryable
methods like Where
or Select
.
So, I would go with your solution until you can fix the database.
来源:https://stackoverflow.com/questions/13454652/can-i-use-data-annotations-or-fluent-to-convert-a-value-between-data-store-and-e