Search code examples
c#asp.netentity-frameworkentity-framework-6ef-code-first

Add item to many to many entity in Entity Framework


So I have these 2 entities

public class Player
{
        [Key]
        public Guid Id { get; private set; }
        public Guid ActiveGroupId { get; set; }
        public virtual Group ActiveGroup { get; set; }
        public virtual ICollection<Group> Groups { get; set; }
}

public class Group
{
        [Key]
        public Guid Id { get; private set; }
        public string Name { get; set; }
        public virtual ICollection<Player> Players { get; set; }
}

So what I wanna do right now is in Configuration.Seed if the players have ActiveGroup and don’t have group yet. Then add the active group to the Player.Groups. Right now I always failed with error Multiplicity constraint violated. The role 'Player_Groups_Source' of the relationship 'Entities.Player_Groups' has multiplicity 1 or 0..1. This is what I did

foreach (var player in context.Players.ToList())
{
    var activeGroup = context.Groups.First(x => x.Id == player.ActiveGroupId);
    player.Groups.Add(activeGroup);
}
context.SaveChanges();

I am using EF 6.4.4 and running it on mac (if that is matter). Any idea what is wrong with this approach?


Solution

  • you need to make sure that your ManyToMany relation is correct defined

    public class PlayerMap : EntityTypeConfiguration<Player>
        {
            public PlayerMap()
            {
                HasMany(a => a.Groups)
                    .WithMany(a => a.Players);
            }
        }
    

    Then you need to initialize the collection of Groups:

    public class Player
    {
        [Key]
        public Guid Id { get; private set; }
        public Guid ActiveGroupId { get; set; }
        public virtual Group ActiveGroup { get; set; }
        public virtual ICollection<Group> Groups { get; set; } = new List<Group>();
    }
    

    then you can add a group to a player.