Based on Ladislav's excellent answer, here's how to do it without using any mappings - just attributes that apply to the model classes themselves:
public class Group { public int Id { get; set; } [MaxLength(300)] public string Name { get; set; } public ICollection<User> Users { get; set; } } public class User { public int Id { get; set; } [MaxLength(300)] public string Name { get; set; } [ForeignKey("PrimaryGroup")] public int PrimaryGroupId { get; set; } [Required] public Group PrimaryGroup { get; set; } [InverseProperty("Users")] public ICollection<Group> SecondaryGroups { get; set; } }
Notes
If you want, you can add the virtual keyword to 2 ICollection and Group . This allows lazy loading . Performance, I do not recommend, but it is possible.
I included MaxLength attributes with an arbitrary (but safe) length of 300 , because when wrapping rows in EF without MaxLength, you get columns with low performance NVarChar(MAX) . It doesn't really matter what they ask, but it's better to post good code.
I recommend the names User and Group for your EF classes against classes. They are going to complicate any SQL that you try to run later, you need to type [User] and [Group] to access them and complicate the use of these classes in MVC controllers, where your User class will conflict with the Context User property that gives you access to the Identity Asp.Net library.
source share