2015-10-21 233 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"); 
相关问题