简体   繁体   English

首先使用Exisitng数据的实体框架代码-如何设置枚举?

[英]Entity Framework Code First With Exisitng Data - How To Setup Enums?

I have tables that are already populatated with item types. 我有已经填充项目类型的表。 How can I use an enum in my code to map new items to those types? 如何在代码中使用枚举将新项目映射到这些类型?

Example: 例:

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 class mapped to the Fruit table 水果类映射到水果表

    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
            };

Do I need to setup a enum in code that matches the FruitType table? 我是否需要在与FruitType表匹配的代码中设置枚举?

FruitTypeID = (int)FruitTypeEnum.Apple

Is there a way that I don't have to have the cast to the int in my code? 有没有一种方法,我不必在代码中强制转换为int

First, Define your enum to match the values in your table: 首先,定义您的枚举以匹配表中的值:

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

Then Set your FruitTypeID property to your enumeration Type 然后将您的FruitTypeID属性设置为您的枚举类型

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

    public FruitType FruitTypeID { get; set; }

    public int Quantity { get; set; }
}

Note, if you want both the enumeration and a virtual foreign key entity defined, then in my testing, I was forced to keep the integer type, for use with the foreign key annotation, and use an unmapped enumeration type property as follows: 请注意,如果要同时定义枚举和虚拟外键实体,则在我的测试中,我被迫保留整数类型以与外键注释一起使用,并使用未映射的枚举类型属性,如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM