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?
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/
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With