2013-02-15 87 views
0

我正在使用教程中的代碼來嘗試在我的真實項目中需要的東西。我在我的DataBase中有一張桌子,裏面有很多(16)Foreign Keys,我不得不使用ADO.NET EF來重新創建整個DataBase,現在我對這個特殊情況有點困惑。下面是我使用的用於測試目的的代碼:在一個表中使用ADO.NET實體框架多個FK

public class Blog 
    { 
     public int BlogId { get; set; } 
     public string Name { get; set; } 
     public string Url { get; set; } 

     public int UserId { get; set; } 
     public virtual User User { get; set; } 

     public virtual List<Post> Posts { get; set; } 
    } 

    public class Post 
    { 
     public int PostId { get; set; } 
     public string Title { get; set; } 
     public string Content { get; set; } 

     //public int BlogId { get; set; } 
     public virtual Blog Blog { get; set; } 

     //public int BlogId1 { get; set; } 
     public virtual Blog Blog1 { get; set; } 

     //public int BlogId2 { get; set; } 
     public virtual Blog Blog2 { get; set; } 

     //public int BlogId3 { get; set; } 
     public virtual Blog Blog3 { get; set; } 

     //public int BlogId4 { get; set; } 
     public virtual Blog Blog4 { get; set; } 
    } 

我評論的int性能,因爲它似乎我不需要他們。執行此代碼,我得到以下幾點:

enter image description here

所以有兩種東西,我關心的那一刻 - 這是在一個表,如果是添加多個Foreign Keys的方式 - 兩行強調了與紅 - 爲什麼我在得到預期的Blog1_.., Blog2_...之前有Blog_BlogIdBlog_BlogId1

回答

0

好吧,我在這裏從我得到的解決方案失去了這篇文章,但在這種特殊情況下,它似乎是某種命名約定,我必須取消評論代碼的註釋並更改名稱而不使用數字或下劃線。然後在OnModelCreating事件添加此代碼很多次,因爲我需要:

modelBuilder.Entity<Post>().HasRequired(c => c.Blog) 
            .WithMany(m => m.Posts) 
            .HasForeignKey(c => c.BlogId) 
            .WillCascadeOnDelete(); 

      modelBuilder.Entity<Post>().HasRequired(c => c.Blogged) 
              .WithMany() 
              .HasForeignKey(c => c.BloggedId) 
              .WillCascadeOnDelete(false); 

請注意,我更改屬性的名稱和類實例名稱我每次添加新紀錄外鍵的時間。