2016-10-24 37 views
1

这是一个有点尴尬,因为我敢肯定的答案很简单。ASP.NET MVC名单串联父表字段

我使用的EntityFramework和代码第一次技术试图建立我的第一功能MVC形式,而以下的优秀ASP.NET教程。

如何显示的字符串,其中包括父信息表被查询。我想在下拉列表中使用的字符串中包含父值......或者我应该以相反的方式执行此操作并选择父项,并让子项显示为选择的结果?

我想,既然它已经在谈论它的父就会像添加到模型一样简单。智能感知是好的与它:-)

模型类

public class SourceLocation 
{ 
    [Key] 
    public int SourceLocationID { get; set; } 
    public int SourceID { get; set; } 

    [Required] 
    [Display(Name = "Product Type")] 
    [StringLength(25)] 
    public string ProductType { get; set; } 

    [Required] 
    [Display(Name = "Source Location")] 
    [StringLength(50)] 
    public string SamplingLocation { get; set; } 
    [Display(Name = "Sampling Location Notes")] 
    public string LocationNotes { get; set; } 
    public string SourceProductType 
    { 
     get 
     { 
      return CementSources.SampleSource + " " + ProductType + " ex " + SamplingLocation; 
     }   
} 

    public virtual CementSource CementSources { get; set; } 
} 

}

该控制器参照SourceSampleType正是如此配置。

// GET: Specifications/Create 
     public ActionResult Create() 
     { 
      ViewBag.FieldID = new SelectList(db.Fields, "FieldID", "FieldName"); 
      ViewBag.SourceLocationID = new SelectList(db.SourceLocations, "SourceLocationID", "SourceProductType"); 
      ViewBag.SpecificationTypeID = new SelectList(db.SpecificationTypes, "SpecificationTypeID", "SpecificationTypeName"); 
      return View(); 
     } 

当我尝试创建其配置为显示SourceSampleType一个新的样本,误差为:


已经没有与此命令必须先关闭相关联的打开的DataReader。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关该错误的更多信息以及源代码的位置。

异常详细信息:System.InvalidOperationException:已经有一个与此命令关联的打开的DataReader,它必须先关闭。

源错误:

Line 28:    get 
Line 29:    { 
Line 30:     return CementSources.SampleSource + " " + ProductType + " ex " + SamplingLocation; 
Line 31:    } 
Line 32:   } 

难道我没有正确使用的语法或者是它的东西与渴望/延迟加载,我还没有解析和理解?

+0

是其涉及到相关的渴望/延迟加载。您需要删除该属性。您可以使用ViewBag.SourceLocationID = db.SourceLocations.AsEnumerable()。Select(x => new SelectListItem {Value = x.SourceLocationID,Text = string.Format(“{0} {1} ex {2}”) x.CementSources.SampleSource,x.ProductType,x.SamplingLocation});' –

+0

快速回复Oarsome感谢所以我杀了的财产,并将此ViewBag到控制器,以便我固定的ToString()位并运行我试图创建一个标本时击中同一DataReader的问题“ 源错误: 线66:ViewBag.SourceLocationID = db.SourceLocations.AsEnumerable()。Select(x => new SelectListItem {Value = x.SourceLocationID.ToString(),Text = string.Format(“{0} {1} ex {2}”,x.CementSources.SampleSource,x.ProductType,x.SamplingLocation )}); ' –

+0

这不应该发生,因为该集合已物化。但尝试使用'db.SourceLocations.Include(x => x.CementSources).AsEnumerable()......' –

回答

0

发生该错误的原因是您迭代了SourceLocation的结果,但在每次迭代中,执行另一个查询以获取其CementSources属性的值。

你需要从模型中取出SourceProductType财产,并使用Include()在查询中包括CementSources