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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0