1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.