连接 select 列表中两个 类 的两个字段

Concatenate two fields from two classes in select list

我需要在 selectList 中连接来自 2 个不同 classes 的两个字段。因此,我在 class 中创建了一个非映射字段,我希望能够基于虚拟字段(指向另一个 table)从中提取该字段。但是,当我尝试 运行 它时,出现了一个奇怪的错误。

这是我的 class 代码:

  [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;
       }
   }

然后是 Select 列表:

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;

然后它起作用了,但当然这不是我要找的结果。状态是此 class 中的另一个字段。

我也尝试过不使用 .ToString() 和使用 .First() - none 有效

当您在数据连接上同时打开两个数据阅读器时,通常会发生该错误。您可以尝试在连接字符串 (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";

您可以尝试枚举查询。

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