将项目添加到 Entity Framework 中的多对多实体

Add item to many to many entity in Entity Framework

所以我有这两个实体

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; }
}

所以我现在想做的是 Configuration.Seed 如果玩家有 ActiveGroup 但还没有组。然后将活动组添加到 Player.Groups。现在我总是因错误 Multiplicity constraint violated. The role 'Player_Groups_Source' of the relationship 'Entities.Player_Groups' has multiplicity 1 or 0..1. 而失败 这就是我所做的

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

我在 mac 上使用 EF 6.4.4 和 运行(如果这很重要)。知道这种方法有什么问题吗?

您需要确保您的 ManyToMany 关系定义正确

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

然后需要初始化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>();
}

然后你可以给一个播放器添加一个组。