2015-10-26 45 views
0

我有已經與項目類型一起使用的表。我如何在代碼中使用枚舉將新項目映射到這些類型?實體框架代碼優先存在數據 - 如何設置枚舉?

實例:映射到水果表

public class Fruit 
    { 
     [Key] 
     public int FruitID { get; set; } 

     public int FruitTypeID { get; set; } 

     public int Quantity { get; set; } 
    } 

Fruit newFruit = new Fruit { 
       FruitTypeID = 1, // How to avoid a magic number here? 
       Quantity = newQuantity 
      }; 

我需要安裝在代碼中枚舉的FruitType表匹配

FruitType Table 
--------------- 
FruitTypeID: 1 
FruitName: "Apple" 
FruitTypeID: 2 
FruitName: "Orange" 
FruitTypeID: 3 
FruitName: "Banana" 
FruitTypeID: 4 
FruitName: "Peach" 

Fruit Table 
----------- 
FruitID: 1 
FruitTypeID: 1 
Quantity: 100 
FruitID: 2 
FruitTypeID: 4 
Quantity: 150 

水果類?

FruitTypeID = (int)FruitTypeEnum.Apple

有沒有,我不必須有投在我的代碼int的方法嗎?

+1

將「FruitTypeID」的類型更改爲「FruitTypeEnum」而不是「int」 – DavidG

回答

0

首先,定義你的枚舉在表中的值匹配:

public enum FruitType{ 
    Apple = 1, 
    Orange = 2, 
    Banana = 3, 
    Peach = 4 
} 

然後你FruitTypeID屬性設置爲你的枚舉類型

public class Fruit 
{ 
    [Key] 
    public int FruitID { get; set; } 

    public FruitType FruitTypeID { get; set; } 

    public int Quantity { get; set; } 
} 

注意,如果你想同時得到枚舉和虛擬外鍵實體定義,然後在我的測試中,我被強制保留整數類型,用於外鍵註釋,並使用未映射的枚舉類型屬性如下:

public class FruitType 
{ 
    [Key] 
    public int FruitTypeID {get;set;} 

    public string FruitName {get;set;} 
} 

public class Fruit 
{ 
    [Key] 
    public int FruitID { get; set; } 

    public int FruitTypeID { get; set; } 

    public int Quantity { get; set; } 

    [NotMapped] 
    public FruitTypeEnum TheFruitTypeEnum { get{ return (FruitTypeEnum)FruitTypeID; } } 

    [ForeignKey("FruitTypeID")] 
    public virtual FruitType TheFruitTypeEntity {get; set;} 
}