EF property of type List not created in db

后端 未结 2 1828
忘了有多久
忘了有多久 2020-12-11 07:47

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

public enum Language : byte
{
    [Display(Name = \"Turkmen\")]
    TKM = 1,
    [D         


        
相关标签:
2条回答
  • 2020-12-11 08:35

    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/

    0 讨论(0)
  • 2020-12-11 08:41

    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; }
    }
    
    0 讨论(0)
提交回复
热议问题