2012-09-03 38 views
5

我遇到了错误的解决方法集合被修改了,枚举操作可能无法执行。 它发生在“作者”和“z”表示相同的元素时。实体框架集合已修改;枚举操作可能不会执行

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.Entity; 

namespace ConsoleApplication1 
{ 
public class Nation 
{ 
    public int ID { get; set; } 
    public int name { get; set; } 
    public virtual ICollection<NationAlly> NationAllys { get; set; } 
} 

public class NationAlly 
{ 
    public int ID { get; set; } 
    public int level { get; set; } 
    public Nation Natio { get; set; } 
} 

public class NationsContext : DbContext 
{ 
    public DbSet<Nation> Nations { get; set; } 
    public DbSet<NationAlly> NationAllys { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Nation>() 
      .HasMany(n => n.NationAllys) 
      .WithRequired() 
      .Map(conf => conf.MapKey("OwnerID")) 
      .WillCascadeOnDelete(false); 

     modelBuilder.Entity<NationAlly>() 
      .HasRequired(a => a.Natio) 
      .WithMany() 
      .Map(conf => conf.MapKey("UserID")) 
      .WillCascadeOnDelete(false); 
    } 
} 


class Program 
{ 



    static void Main(string[] args) 
    { 
     using (var context = new NationsContext()) 
     { 

      // We have three Nations and two Allies 
      Nation nation1 = new Nation() 
      { 
       name = 1 
      }; 
      Nation nation2 = new Nation() 
      { 
       name = 2 
      }; 
      Nation nation3 = new Nation() 
      { 
       name = 3 
      }; 



      context.Nations.Add(nation1); 
      context.Nations.Add(nation2); 
      context.Nations.Add(nation3); 

      context.SaveChanges(); 

     } 



     using (var context = new NationsContext()) 
     { 
      Nation z = (from x in context.Nations 
         where x.name == 1 
         select x).FirstOrDefault(); 


      Nation author = (from x in context.Nations 
          where x.name == 1 
          select x).ToList().FirstOrDefault(); 

      NationAlly ally1 = new NationAlly() 
      { 
       Natio = author 
      }; 

      // toNation of ally1 refers to Nation2 
      // ally1.User = author; 


      if (z.NationAllys != null) 
      { 
       z.NationAllys.Add(ally1); 
      } 
      else 
      { 
       z.NationAllys = new List<NationAlly>(); 
       z.NationAllys.Add(ally1); 
      } 




      context.SaveChanges(); 




     } 
    } 


} 

} 

我测试的代码上的实体框架4.1和5

回答

4

如果添加ally1的环境下,你已经创造了它之后immedately它的工作原理:

//... 
NationAlly ally1 = new NationAlly() 
{ 
    Natio = author 
}; 
context.NationAllys.Add(ally1); 
//... 

的问题有用你在特例中的循环引用做...

z - > z.NationAllys包含ally1 - > ally1指作者= Z

...并很可能与此相关的一个:

EF 4.1 and "Collection was modified; enumeration operation may not execute." exception

我真的不能解释它,但它看起来像一个EF臭虫把我当成你的代码应该没有工作问题。

+0

是的!谢谢。我的问题也是自引用类型,我试图向EF表明有明确的双向引用。删除child->父引用后,它工作正常! –

-1

问题与您的循环引用有关。您应该将零分配给某些参考以避免循环

相关问题