我有已经使用项目类型的表格。如何在代码中使用枚举将新项目映射到这些类型?
示例:
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
水果类映射到Fruit表
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表匹配的代码中设置枚举?
FruitTypeID = (int)FruitTypeEnum.Apple
有没有办法让我不必在我的代码中使用int
投射?
答案 0 :(得分: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;}
}