开发者

Self referencing model in EF Code First 4.1 throws 'Collection was modified' exception

开发者 https://www.devze.com 2023-03-30 23:57 出处:网络
I am trying to model the following using EF 4.1 and cannot get past this exception (\"Collection 开发者_高级运维was modified; enumeration operation may not execute\").

I am trying to model the following using EF 4.1 and cannot get past this exception ("Collection 开发者_高级运维was modified; enumeration operation may not execute").

Models:

public class Workflow
{
    public List<WorkflowStage> Stages { get; set; }
}

public class WorkflowStage
{
    public virtual List<WorkflowNextStage> WorkflowNextStages { get; set; }
}

public abstract class WorkflowNextStage
{
    public virtual WorkflowStage NextStage { get; set; }
}

public class SuccessStage : WorkflowNextStage
{
}

public class FailureStage : WorkflowNextStage
{
}

Configuration:

    modelBuilder.Entity<WorkflowStage>()
            .HasMany(x => x.WorkflowNextStages)
            .WithRequired()
            .Map(m => m.MapKey("CurrentStageId"));

    modelBuilder.Entity<WorkflowNextStage>()
            .HasRequired(x => x.NextStage)
            .WithMany()
            .Map(x => x.MapKey("NextStageId"))
            .WillCascadeOnDelete(false);

Failing code:

    using (var ctx = new SBContext())
        {
            var workflow = new Workflow();
            var stage = new WorkflowStage();
            stage.WorkflowNextStages = new List<WorkflowNextStage>
                                           {
                                               new SuccessStage() {NextStage = stage},
                                               new FailureStage() {NextStage = stage}
                                           };

            workflow.Stages = new List<WorkflowStage> {stage};

            ctx.Workflows.Add(workflow);
            ctx.SaveChanges();
        }

Setting the 'new SuccessStage' above to a different stage works just fine.

I am a bit stumped on this one...anyone have any ideas?


Do you have a foreach loop where you are iterating through the collection you are modifying? If so this may cause this error.

0

精彩评论

暂无评论...
验证码 换一张
取 消