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(),
注释,那么它工作正常。
我错过了什么吗?