2015-02-11 100 views
0

從帖子中提取: Define one-to-one in EF code first with fluent API 在那裏我無法獲得一對一的工作,現在我遇到了另一個一對多的問題。首先無法獲得EF代碼的一對多工作

這裏是我的兩個類:

[Table("PSCStatuses")] 
public class PSCStatus 
{ 
    [Key] 
    public int PSCStatusID { get; set; } 
    public string StatusCode { get; set; } 
    public string StatusTextDesc { get; set; } 
    public int NumDaysToProjEndDate { get; set; } 

    public virtual List<Case> Cases { get; set; } 
} 

public class Case 
{ 
    // Key: Tells EF this is the PK for Case. 
    // ForeignKey("Appointee"): tells EF Appointee is the Principle/Parent in the 1:1 
    [Required] 
    [Key, ForeignKey("Appointee")] 
    public string ProfileID { get; set; } 

    [Required] 
    public int? PSCStatusID { get; set; } 

    public virtual PSCStatus PSCStatus { get; set; } 
    public virtual Appointee Appointee { get; set; } 
} 

你可以在這裏看到我在我以前的帖子做的就是案例有一個特派員。 (並且被任命爲受委人是原則/家長的情況)。 我不記得曾經用EF來過關。但我覺得我在這裏很生疏。

現在解決後,我有一個新問題。 我無法獲得Case來填寫PSCStatus。 當我在添加具有PSCstatusID集合的案例之後在斷點處檢查Case.PSCStatus時,我應該看到填充並填充了PSCStatus對象。 但它仍然爲空。 我認爲上面的定義會告訴EF它需要知道的一切,但它不起作用。

我也嘗試一口流利的API:使用

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Case>() 
        .HasRequired<PSCStatus>(c => c.PSCStatus) 
        .WithMany(s => s.Cases) 
        .HasForeignKey(c => c.PSCStatusID); 
    } 
+0

你在檢查前如何得到物體它在一個斷點?你是否確定要加載PSCStatus? – DrewJordan 2015-02-11 16:50:40

回答

0

: INSEAD的List

[編輯]

如果這不起作用試試這個模型生成ICollection

modelBuilder.Entity<Case>() 
     .HasRequired(c => c.PSCStatus) 
     .WithMany(s => s.Cases) 
     .HasForeignKey(c => c.PSCStatusID); 
+0

對於延遲加載工作,類型必須實現'ICollection',訪問必須是'public'或'protected'。 – 2015-02-11 16:15:26

+0

謝謝 - 我嘗試過,但仍然沒有運氣。 我只是不知道爲什麼EF不聽我的導航屬性和外鍵屬性。 – Sam 2015-02-11 16:33:33

+0

是的,把它作爲ICollection,但仍然不起作用。 – Sam 2015-02-11 16:36:31