LINQ 内部联接,然后选择项下拉列表



我想将数据库中的结果拉到选择下拉框中。我想做的是有一个选择下拉框,显示数据库中的选定值以及列表中的其他值。CommDept表中的CommDeptID和DeptText字段包含1 HR,2管理,3 IT等值。LocationID 等于 CommDeptID。

我收到此错误:

无法将类型"System.Linq.IQueryable<>"隐式转换为"IntranetSite.Models.Communications"。存在显式转换(您是否缺少强制转换?

通信是我的模型,看起来像这样:

[Key]
public int CommunicationsID { get; set; }
[Required(ErrorMessage = "Enter Title")]
public string Title { get; set; }
[Required(ErrorMessage = "Select Location")]
public int LocationID { get; set; }
[Required(ErrorMessage = "Select Message Type")]
public int MessageTypeID { get; set; }
[Required(ErrorMessage = "Enter Message")]
public string Message { get; set; }
public DateTime EnteredDateTime { get; set; }

位置 ID 是我的通信表中的一个字段,也是我的 CommDept 表中的一个字段。

[Key]
public int CommDeptID { get; set; }
public string DeptText { get; set; }

我的代码:

var data = from c in _Context.Communications
join d in _Context.CommDept on c.LocationID equals d.CommDeptID
where c.CommunicationsID == id
select new
{
c.CommunicationsID,
c.Title,
c.MessageTypeID,
c.Message,
c.LocationID,
d.DeptText
};
Communications = data;
LocationID = _Context.CommDept
.Select(a => new SelectListItem
{
Value = a.CommDeptID.ToString(),
Text = a.DeptText,
Selected = a.CommDeptID == c.LocationID
})
.ToList();

您选择的新语句正在创建新的匿名类型。然后,您尝试将其隐式转换为通信模型。不要只说"选择新建",而是尝试选择特定类型的新实例,而不是匿名类型。

另一个问题是您没有使用从 Linq 语句返回的数据。然后,您尝试在新语句中使用顶部 linq 查询中的别名 c。我会把它们合并成一个声明。

假设位置 ID 是选择列表,请尝试以下操作:

var myList = new SelectList(new List<SelectListItem>{
from c in _Context.Communications
join d in _Context.CommDept
on c.LocationID equals d.CommDeptID
where c.CommunicationsID == id
select new SelectListItem
{
Value = d.CommDeptID.ToString(),
Text = d.DeptText,
Selected = d.CommDeptID == c.LocationID
}
}.ToList());

我没有自己运行这个,所以仔细检查代码。您也可以在此处查看更多信息: 如何在 MVC 剃须刀中生成下拉列表 asp.net

最新更新