Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF property of type List<enum> not created in db

I'm developing an ASP.NET MVC5 application using code first EF. My code:

public enum Language : byte
{
    [Display(Name = "Turkmen")]
    TKM = 1,
    [Display(Name = "Russian")]
    RUS = 2,
    [Display(Name = "Chineese")]
    CHN = 3,
    [Display(Name = "English")]
    ENG = 4
}

And my model class is:

public class Person
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int PersonID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Surname { get; set; }

    public virtual List<Enums.Language> Languages { get; set; }

    public Person()
    {
        Languages = new List<Enums.Language>();
    }
}

After I build application and Update-Database in package manager console in VS 2013 I can not find a reference table for Persons languages. I thought a table with a name Person_Languages (or similar) with PersonID and LanguageID should be created. What did I wrong or missed?

like image 427
Dovlet Mamenov Avatar asked Feb 10 '15 10:02

Dovlet Mamenov


2 Answers

Use Flag Enum. You don't need any additional tables. It is much more faster.

In your model you can do

var person = new Person();
p.Languages.Add(Language.TKM);
p.Languages.Add(Language.TKM); // Add the same language twice

... which is wrong. With flag you will do like that

p.Languages = Language.TKM | Language.RUS;

http://blog.falafel.com/entity-framework-enum-flags/

like image 76
rodpl Avatar answered Nov 05 '22 14:11

rodpl


I can't clearly reference my response but: an enum is not a class so it can't be an entity.

In you case you have to create a language class:

public class CLanguage
{
    public Int32 Id { get; set; }
    public Language Lang { get; set; }
}

and then:

public class Person
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int PersonID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Surname { get; set; }

    public virtual ICollection<CLanguage> Languages { get; set; }

    public Person()
    {
        Languages = new List<CLanguage>();
    }
}

Please note the use of ICollection instead of List for compliance.

You may also want to use the enum property as PK.

public class CLanguage
{
    [Key]    
    public Language Lang { get; set; }
}
like image 43
tschmit007 Avatar answered Nov 05 '22 16:11

tschmit007