0
我在實體框架的核心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);
});
}
}
我試圖創建一個問題列表(在下面的代碼我只加一):
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();
當添加我得到以下錯誤的問題:
System.AggregateException occurred
InvalidOperationException: Collection was modified; enumeration operation may not execute.
這是工作EntityFramework 1.0.1。遷移到1.1時出現錯誤。
如果我在Answer中的代碼行Author = context.Users.Last(),
註釋,那麼它工作正常。
我錯過了什麼嗎?