[英]Entity Framework Code First With Exisitng Data - How To Setup Enums?
我有已经填充项目类型的表。 如何在代码中使用枚举将新项目映射到这些类型?
例:
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
水果类映射到水果表
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
?
首先,定义您的枚举以匹配表中的值:
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;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.