确定类型" var"的列表变量的计数。

时间:2016-11-14 12:50:38

标签: asp.net-mvc entity-framework

如果ViewBag.Job_CoId2有记录,我想设置CoId2,但我在第三行得到以下错误!

  SelectList Job_CoId = 
      new SelectList(db.COM_Company.OrderBy(a => a.COM_Name), "COM_ID", "COM_Name");
  var CoId2 = db.Job_CoId2
      .Where(a => a.IDMainCo == Job_CoId.First().Value);
  if ((CoId2.Count()) > 0)
         ViewBag.Job_CoId2 = 
             new SelectList(CoId2.OrderBy(a => a.rank), "ID", "Name");
  

无法创建类型的常量值   ' System.Web.Mvc.SelectListItem&#39 ;.只有原始类型或枚举   在这种情况下支持类型。

2 个答案:

答案 0 :(得分:1)

您的问题似乎是您需要SelectListItems列表(例如List<SelectListItem>)而不是SelectList

//you may need to call .ToString() on non varchar columns such as your ID
 List<SelectListItem> Job_CoId = db.COM_Company.OrderBy(a => a.COM_Name)
  .Select(a=>new SelectListItem{Name = a.COM_Name, Value = a.COM_ID}).ToList();

   //make sure Job_CoId has something else call .First() will fail
   var CoId2 = db.Job_CoId2.Where(a => a.IDMainCo == Job_CoId.First().Value);
   if ((CoId2.Count()) > 0){
     //we actually need a List<SelectListItem> for the view
     ViewBag.Job_CoId2 = CoId2.OrderBy(a => a.rank)
     .Select(r => new SelectListItem { Name = r.Name, Value = r.Id}).ToList();
   }
   else{
       //null ref exception if you try and call this and nothing here
       ViewBag.Job_CoId2 = new List<SelectListItem>();
   }

现在,我认为我们可以清理它,因为我们可以在第二个下拉列表中组合您的一些调用。另外,请注意SelectListItem会将Name和Value都转换为字符串,因此您可能需要在第二个查询中转换回EF中的基元类型。

List<SelectListItem> Job_CoId = db.COM_Company.OrderBy(a => a.COM_Name)
      .Select(a=>new SelectListItem{Name = a.COM_Name, Value = a.COM_ID.ToString()}).ToList();
if(Job_CoId.Any()){
    //ID will be a string coming out of select list.
    //may need to recast to an int for DB comparisons
    var intId = int.Parse(Job_CoId.First().Value);
    ViewBag.Job_CoId2 = db.Job_CoId2.Where(a => a.IDMainCo == intId)
      .OrderBy(a => a.rank)
      .Select(r => new SelectListItem { Name = r.Name, Value = r.Id}).ToList();    
}else{
    ViewBag.Job_CoId2 = new List<SelectListItem>();
}

答案 1 :(得分:0)

将CoId2设为.TOLIST():'

  var Job_CoId = db.COM_Company.Select(x=>x.COM_ID).ToList();
  var CoId2 = db.Job_CoId2.Where(a => a.IDMainCo == Job_CoId.First().Value);
   if ((CoId2.Count()) > 0)
     ViewBag.Job_CoId2 = new SelectList(CoId2.OrderBy(a => a.rank).ToList(), "ID","Name");