1

我有一個代碼,第一種模式:爲什麼我的實體框架POCO不能正確加載相關實體?

namespace InternetComicsDatabase.Models 
{ 
    public class Issue 
    { 
     [Key] 
     public int  IssueId  { get; set; } 
     public int  Number  { get; set; } 
     public string Title  { get; set; } 
     public DateTime Date  { get; set; } 

     public virtual ICollection<Creator> Creators { get; set; } 
    } 

    public class Creator 
    { 
     [Key] 
     public int  CreatorId { get; set; } 
     public string FirstName { get; set; } 
     public string MiddleName { get; set; } 
     public string LastName { get; set; } 

     public virtual ICollection<Issue> Issues { get; set; } 
    } 

    public class Icbd : DbContext 
    { 
     public DbSet<Issue> Issues { get; set; } 
     public DbSet<Creator> Creators { get; set; } 
    } 
} 

在控制器中,我試圖加載與特定問題相關聯的所有Creators

public string CreatorTest() 
    { 
     string output = ""; 
     var issue = db.Issues.Where(x => x.IssueId == 8); 
     foreach (var item in issue.Creators) 
      output += item.FirstName; 
     return output; 
    } 

但這不會編譯。 ..爲什麼不能編譯?

具體而言;

 foreach (var item in issue.Creators) 

不會因爲一個錯誤,指出的編譯:這行

Error 1 'System.Linq.IQueryable<InternetComicsDatabase.Models.Issue>' does not contain a definition for 'Creators' and no extension method 'Creators' accepting a first argument of type 'System.Linq.IQueryable<InternetComicsDatabase.Models.Issue>' could be found (are you missing a using directive or an assembly reference?) C:\Users\dropstuff\asp.net mvc\InternetComicsDatabase\InternetComicsDatabase\Controllers\HomeController.cs 19 31 InternetComicsDatabase 

是什麼回事? :-)

我回去並重新檢查我的控制器(你可以向上滾動),是的;它是! Creators財產Issues。那麼是什麼給了?也許它與延遲加載有關?

回答

1

您的查詢是錯誤的。您想要:

var issue = db.Issues.Where(x => x.IssueId == 8).Single(); 

您期待的是單個問題,而不是一個問題的列表。

2

嘗試使用Single()代替Where()db.Issues.Where(x => x.IssueId == 8)

var issue = db.Issues.Single(x => x.IssueId == 8);