EntityFramework pence to pounds

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?

Answers


You might want to try something like this

public class YourClassName {
   public decimal Price { get; set; }

   [NotMapped]
   public decimal Pounds => Price/100;
}

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().


Need Your Help

how to declare and use object in this build.sbt?

scala sbt

I am trying to understand how to write a well-written build.sbt file, and followed a tutorial on youtube. In that tutorial an object is created similar as below, but what I have written gives the s...

Moving to IasS on MS Azure

azure iaas

We have got an application running fine on On premises and plan to move it to IaaS on Ms Azure, do we need to make any changes to it or will it work as is?