问题
I'm building a WPF application. I made my database using Code-First.
I need to insert prices of items in pence (e.g. 500), but when prices will be displayed they should be in pounds (5,00).
I tried to do the "conversion" in the setter of my property
public decimal Price
{
get { return price; }
set { price = value/100 ;}
}
But, for some reason, when I drop manually the database, the values in my ListView
are shown some times like 0,05 and other times like 500,00. Something must be wrong with this method.
How can I tell my database to consider last 2 numbers of my value as decimal?
回答1:
You might want to try something like this
public class YourClassName {
public decimal Price { get; set; }
[NotMapped]
public decimal Pounds => Price/100;
}
回答2:
In Entity Framework, the value returned by the "getter" is what will be stored to the database. Therefore, anything you set on this property is going to be value/100.
What you want to do is establish a standard way you want to store the currency. Probably in this case, "Pence" is best, and I'd re-word the property to make it self documenting (and remove the division).
public decimal PriceInPence
{
get { return price; }
set { price = value;}
}
Then I'd supply a method for getting the Pounds:
public decimal GetPriceInPounds()
{
return price == 0m ? 0m : price/100m;
}
If you're using the MVVM pattern as hinted to by one of your question comments, you'd populate the view model with calls to GetPriceInPounds().
来源:https://stackoverflow.com/questions/34005590/entityframework-pence-to-pounds