Can I use Data Annotations or Fluent to convert a value between data store and entity class?

心不动则不痛 提交于 2020-01-05 07:28:40

问题


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

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