EntityFramework pence to pounds

喜欢而已 提交于 2019-12-13 10:27:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!