C# 首先使用现有数据编写实体框架代码-如何设置枚举?
我有一些已经填充了项类型的表。如何在代码中使用枚举将新项映射到这些类型 例如:C# 首先使用现有数据编写实体框架代码-如何设置枚举?,c#,entity-framework,C#,Entity Framework,我有一些已经填充了项类型的表。如何在代码中使用枚举将新项映射到这些类型 例如: FruitType Table --------------- FruitTypeID: 1 FruitName: "Apple" FruitTypeID: 2 FruitName: "Orange" FruitTypeID: 3 FruitName: "Banana" FruitTypeID: 4 FruitName: "Peach" Fruit Table ----------- FruitID:
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
};
我是否需要在代码中设置一个与水果类型表匹配的枚举
FruitTypeID=(int)FruitTypeEnum.Apple
是否有一种方法不必强制转换到代码中的
int
?首先,定义枚举以匹配表中的值:
public enum FruitType{
Apple = 1,
Orange = 2,
Banana = 3,
Peach = 4
}
然后将您的水果类型ID属性设置为枚举类型
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;}
}
将
grouttypeid
的类型更改为grouttypeenum
而不是int