I would use the free API:
public class Context : DbContext { public DbSet<User> Users { get; set; } public DbSet<Group> Groups { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<User>() .HasMany(u => u.Groups) .WithMany(g => g.Members); modelBuilder.Entity<User>() .HasMany(u => u.OwnedGroups) .WithRequired(g => g.Owner) .WillCascadeOnDelete(false); } }
This should also be possible with data annotations:
public class User { ... [InverseProperty("Owner")] public virtual ICollection<Group> OwnedGroups { get; set; } [InverseProperty("Members")] public virtual ICollection<Group> Groups { get; set; } } public class Group { ... [InverseProperty("OwnedGroups")] public virtual User Owner { get; set; } [InverseProperty("Groups")] public virtual ICollection<User> Members { get; set; } }
InverseProperty not required on both sides of the relationship, but it makes the definition clearer.
source share