2016-12-27 91 views
0

如何從我的數據庫中讀取int屬性,該屬性在我的系統中是存儲庫模式C#中的Enumeration類型屬性。枚舉存儲庫模式c#

我做了一個類:

public class Status : Enumeration 
{ 
    public static readonly Status Active = new Status(0, "Active"); 
    public static readonly Status Inactive = new Status(1, "Inactive"); 
    public static readonly Status Removed = new Status(2, "Removed"); 

    public Status() 
    { 
    } 

    private Status(int value, string displayName) 
     : base(value, displayName) 
    { 
    } 
} 

所以在銀行類,我把一個狀態屬性;

在從我的Bank類所在的銀行讀取數據時,以及具有屬性Status類型int的表格,並且該屬性獲取爲空時。

+0

你好,歡迎來到StackOverflow。請花一些時間閱讀幫助頁面,尤其是名爲[「我可以詢問什麼主題?」(http://stackoverflow.com/help/on-topic)和[「我應該問什麼類型的問題避免問?「](http://stackoverflow.com/help/dont-ask)。更重要的是,請閱讀[Stack Overflow問題清單](http://meta.stackexchange.com/q/156810/204922)。您可能還想了解[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

+0

你使用EntityFramework還是普通的ADO.net? –

+0

ADO.net與DapperRepository – Dariel

回答

0

我會介紹一個靜態方法來整數轉換爲「枚舉」在你的類,例如

public class Status : Enumeration 
    { 
     //YOUR CODE 

     public static Status FromInteger(int value){ 
     switch(value){ 
      case 0: 
      return Active; 
      case 1: 
      return Inactive; 
      case 2: 
      return Removed; 
      default: 
      throw new ArgumentException(); 
     } 
     } 
    } 

我沒有處理DapperRepository。但快速查看ClassMapper<T>顯示您可以使用AutoMap方法自定義轉換。但是,我沒有發現文檔和示例。 因此,我只能提出一個通用的解決方案。

public class Bank { 

     //Standard fields that are mapped to a table in database 

     public Status StatusEnum { 
     get { 
      Status.FromInteger(StatusId); //StatusId is a property mapped to table's field 
     } 

     set { 
      //TODO Handle null value 
      StatusId = value.Value; 
     } 
     } 
    } 

注:

  • 我認爲財產StatusId是映射到包含狀態值表的字段的字段。
  • 此代碼有明顯問題 - StatusId允許超出枚舉範圍的值。你將不得不做一些額外的驗證來保持數據的一致性。
+0

非常感謝 – Dariel