我遇到了其他相同问题的帖子,但都没有得到回答,但并没有放弃。我正在做一个与D&D相关的项目,我有Encounters和Creatures,它们通过EncounterCreatures有很多对很多的关系。
模型生物:
public ICollection<EncounterCreatures> Encounters { get; set; }
//Unshadowing
public int UserId { get; set; }
public User User { get; set; }
遇到模型:
public ICollection<EncounterCreatures> Creatures { get; set; }
//Unshadowing
public int UserId { get; set; }
public User User { get; set; }
模型遭遇生物:
public int CreatureId { get; set; }
public int EncounterId { get; set; }
public Encounter Encounter { get; set; }
public Creature Creature { get; set; }
相关的DBContext片段:
//Creatures
modelBuilder.Entity<Creature>().HasKey(c => c.Id);
modelBuilder.Entity<Creature>().HasMany(e => e.Encounters); //EncounterCreatures
//Encounter
modelBuilder.Entity<Encounter>().HasKey(e => e.Id);
modelBuilder.Entity<Encounter>().HasMany(ec => ec.Creatures).WithOne(e => e.Encounter).HasForeignKey(e => e.EncounterId)
//.OnDelete(DeleteBehavior.Cascade);
.OnDelete(DeleteBehavior.NoAction);
//Composite Keys
modelBuilder.Entity<EncounterCreatures>().HasKey(ec => new { ec.EncounterId, ec.CreatureId });
如果我未指定.OnDelete NoAction,则会收到此错误,无法创建数据库: 在表'EncounterCreatures'上引入FOREIGN KEY约束'FK_EncounterCreatures_Encounters_EncounterId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。
但是后来我无法删除我的遭遇,因为我会收到此错误: System.InvalidOperationException: 实体类型“ Encounter”和“ EncounterCreatures”之间的关联已被切断,但是由于外键不可为空,因此该关系被标记为“ Required”或隐式必需。 如果在切断所需的关系时应删除从属/子实体,请设置该关系以使用级联删除。
我确实想在删除Encounter时删除EncounterCreatures,所以我想设置级联删除,但这会使我回到第一个错误。
为Gert Arnold编辑:
modelBuilder.Entity<User>().HasMany<Character>(u => u.Characters).WithOne(u => u.User).HasForeignKey(u => u.UserId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<User>().HasMany<Encounter>(u => u.Encounters).WithOne(u => u.User).HasForeignKey(u => u.UserId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<User>().HasMany<Creature>(u => u.Creatures).WithOne(u => u.User).HasForeignKey(u => u.UserId);
用户模型:
public ICollection<Character> Characters { get; set; }
public ICollection<Encounter> Encounters { get; set; }
public ICollection<Creature> Creatures { get; set; }