2016-08-20 216 views
1

即時通訊學習實體框架,並已悲慘地失敗與這項任務幾天...我想實現以下數據庫計劃:實體框架一對多和多對多的關係

TableA: 
ClassA_ID 
ClassB_ID(foreign key - one to one) 

TableATableB:(one-to-many relationship) 
ClassA_ID 
ClassB_ID 

TableB: 
ClassA_ID(foreign key - one to one) 
ClassB_ID 

所以我實際上想要從A類到B類的特定一對一關係和從ClassA到ClassB的一對多關係。

我的C#代碼如下所示:

A類:

public static int idcounter; 
[Key] 
public int id { get; set; } 
public virtual List<ClassB> allClassB { get; set; } 
public virtual ClassB currentClassB { get; set; } 
public int? currentClassBID { get; set; } 

public ClassA(){ 
    idcounter++; 
    id = idcounter; 
    allClassB = new List<ClassB>(); 
    currentClassB = new ClassB(); 
    currentClassBID = currentClassB.id; 
    MyContext.add(this); 
} 

B類:

public static int idcounter; 
[Key] 
public int id { get; set; } 
public virtual ClassA owner { get; set; } 
public int? ownerID { get; set; } 

public ClassB(ClassA a){ 
    idcounter++; 
    id = idcounter; 
    owner = a; 
    ownerID = a.id; 
} 

MyContext:

這個問題
public static void add(ClassA a) 
    { 
     using (MyContext context = new MyContext()) 
     { 
      context.setB.Add(a.currentClassB); 
      context.setA.Add(a); 
      context.SaveChanges();   
     } 
    } 

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<ClassA>().HasOptional(x => x.currentClassB).WithMany().HasForeignKey(x => x.currentClassBID).WillCascadeOnDelete(false); 
     modelBuilder.Entity<ClassB>().HasOptional(x => x.ClassA).WithMany(x => x.allClassB).HasForeignKey(x => x.ownerID).WillCascadeOnDelete(false) ; 
    } 

它非常相似 Entity Framework Code First: How can I create a One-to-Many AND a One-to-One relationship between two tables? 但保存時我只是得到一個循環異常。

Unable to determine a valid ordering for dependent operations. Dependencies may 
exist due to foreign key constraints, model requirements, or store-generated 
values. 

它很奇怪的是

context.setA.Add(a); 

它添加到currentClassB沒有allClassB我過上提,......它甚至突然確實,當我不

allClassB = new List<ClassB>(); 

我是什麼做錯了?

+0

誰需要編碼規範啊? – Sinjai

回答