2015-10-21 232 views
0

我需要連接2個不同類別的兩個字段中選擇列表的。所以我在這個類中創建了一個非映射的字段,我希望能夠從一個虛擬字段(指向另一個表)獲取這個字段。但是,當我嘗試運行它時,出現了一個奇怪的錯誤。連接兩個來自兩個班字段選擇列表

這裏是我的類代碼:

[Display(Name = "Problem")] 
    [ForeignKey("Problem")] 
    [Required] 
    public Guid ProblemId { get; set; } 

    public virtual Problem Problem { get; set; } 

    [Display(Name = "Category")] 
    [NotMapped] 
    public string FullCategory 
    { 
     get 
     { 
      return "(" + this.Problem.ProblemName.ToString() + ") " + CategoryName; 
     } 
    } 

,然後選擇列表:

ViewBag.CategoryId = new SelectList(db.Categories.Where(c => c.Status == 1).OrderBy(c => c.Problem.ProblemName), "CategoryId", "FullCategory"); 

和崩潰在這條線:

return "(" + this.Problem.ProblemName.ToString() + ") " + CategoryName; 

與此錯誤:

{"There is already an open DataReader associated with this Command which must be closed first."}

不過,如果我更改代碼這樣:

return "(" + Status + ") " + CategoryName; 

那麼它的工作原理,但當然這不是我期待的結果。狀態是這個班的另一個領域。

我也試了一下沒有的ToString()和我。首先()試了一下 - 他們沒有工作

+0

返回之前你是高達任何數據連接? –

回答

0

該錯誤通常當你有兩個數據的讀者在同一時間上的數據時開放連接。您可以嘗試在連接字符串上啓用多個活動結果集(https://msdn.microsoft.com/en-us/library/h32h3abf%28v=vs.110%29.aspx)。

string connectionString = "Data Source=myDataSource;" + 
    "Initial Catalog=myCatalog;Integrated Security=mySecurity;" + 
    "MultipleActiveResultSets=True"; 
0

您可以嘗試枚舉查詢。

ViewBag.CategoryId = new SelectList(
    db.Categories 
     .Include("Problem") // eager load 
     .Where(c => c.Status == 1) 
     .OrderBy(c => c.Problem.ProblemName) 
     .ToList(), // enumerate 
    "CategoryId", 
    "FullCategory"); 
相關問題