0
I持ってEntity Frameworkのコア1.1の次のエンティティ:System.AggregateExceptionが発生しました - コレクションが変更された
public class Question {
public Int32 Id { get; set; }
public Int32 AuthorId { get; set; }
public String Content { get; set; }
public virtual User Author { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
public class Answer {
public Int32 Id { get; set; }
public Int32 QuestionId { get; set; }
public Int32 AuthorId { get; set; }
public String Content { get; set; }
public virtual Question Question { get; set; }
public virtual User Author { get; set; }
}
public class User : IdentityUser<Int32> {
public virtual ICollection<Answer> Answers { get; set; } = new List<Answer>();
public virtual ICollection<Question> Questions { get; set; } = new List<Question>();
}
public class Context : IdentityDbContext<User, Role, Int32> {
public DbSet<Answer> Answers { get; set; }
public DbSet<Question> Questions { get; set; }
public Context(DbContextOptions<Context> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder) {
base.OnModelCreating(builder);
builder.Entity<Question>(b =>
b.ToTable("Questions");
b.HasKey(x => x.Id);
b.Property(x => x.Content).HasMaxLength(400).IsRequired(true);
b.HasOne(x => x.Author).WithMany(x => x.Questions).HasForeignKey(x => x.AuthorId).IsRequired(true).OnDelete(DeleteBehavior.Restrict);
});
builder.Entity<Answer>(b =>
b.ToTable("Answers");
b.HasKey(x => x.Id);
b.Property(x => x.Content).HasMaxLength(4000).IsRequired(true);
b.HasOne(x => x.Author).WithMany(x => x.Answers).HasForeignKey(x => x.AuthorId).IsRequired(true).OnDelete(DeleteBehavior.Restrict);
b.HasOne(x => x.Question).WithMany(x => x.Answers).HasForeignKey(x => x.AuthorId).IsRequired(true).OnDelete(DeleteBehavior.Cascade);
});
}
}
私は(私は一つだけを追加してい次のコードで)質問のリストを作成しようとしました:
System.AggregateException occurred
InvalidOperationException: Collection was modified; enumeration operation may not execute.
これは働いていた:私は次のエラーを取得する質問を追加する場合
List<Question> questions = new List<Question>();
questions.Add(new Question {
Approved = DateTime.UtcNow,
Author = context.Users.First(),
Content = "question",
Created = DateTime.UtcNow,
IsApproved = true,
Level = context.Levels.First(),
Updated = DateTime.UtcNow,
Answers = new List<Answer> {
new Answer {
Approved = DateTime.UtcNow,
Author = context.Users.Last(),
Content = "answer",
Created = DateTime.UtcNow,
IsApproved = true,
Updated = DateTime.UtcNow
}
}
});
context.AddRange(questions);
await context.SaveChangesAsync();
EntityFramework 1.0.1。 1.1に移行するときにエラーが発生しました。
回答のコード行Author = context.Users.Last(),
にコメントしても問題ありません。
何か不足していますか?