c# - 将项目添加到实体框架中的多对多实体
问题描述
所以我有这两个实体
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();
我正在使用 EF 6.4.4 并在 mac 上运行它(如果有的话)。知道这种方法有什么问题吗?
解决方案
你需要确保你的 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>();
}
然后您可以将组添加到播放器。
推荐阅读
- python - 如何将思维导图csv转换为python dict并找到密钥
- java - 使用枚举,错误:org.apache.crunch.CrunchRuntimeException:java.lang.NoSuchMethodException:
- time - 将假设参数的值添加到 Power BI 中的时间值
- ios - 加载预加载到 Core Data 中的 SQLite 数据库
- unit-testing - BDD Mockito - 使用参数捕获器时验证(...)的别名?
- css - 在Flask中使用子域时,如何访问css url中引用的静态文件和使用require.js的js文件?
- angular - Angular6 ngrx:无法读取未定义的属性“ID”
- python - 我想在熊猫中对列进行分组
- python - Pandas + sqlalchemy:通过 pandas 将多个特定列从 csv 提取到 sqlite
- html - ASP.NET Web 应用程序 - Web 表单 - HTML 问题