LINQ内部联接和选择项下拉列表
我想将结果从数据库拉入选择下拉框。我想做的是有一个选择下拉框,显示数据库中的选定值以及列表中的其他值。CommDept表中的字段CommDeptID和DeptText中有值,如1小时、2次管理、3次it等。LocationID等于CommDeptID 我得到这个错误: 无法将类型“System.Linq.IQueryable”隐式转换为“IntranetSite.Models.Communications”。存在显式转换。是否缺少强制转换 通信是我的模型,如下所示:LINQ内部联接和选择项下拉列表,linq,razor,Linq,Razor,我想将结果从数据库拉入选择下拉框。我想做的是有一个选择下拉框,显示数据库中的选定值以及列表中的其他值。CommDept表中的字段CommDeptID和DeptText中有值,如1小时、2次管理、3次it等。LocationID等于CommDeptID 我得到这个错误: 无法将类型“System.Linq.IQueryable”隐式转换为“IntranetSite.Models.Communications”。存在显式转换。是否缺少强制转换 通信是我的模型,如下所示: [Key] public i
[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; }
LocationID是我的通讯表中的一个字段,也是我的通讯部门表中的一个字段
[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();
select new语句正在创建新的匿名类型。然后,您试图隐式地将其转换到通信模型中。不要只说selectnew,而是尝试选择特定类型的新实例,而不是匿名类型 另一个问题是您没有使用从Linq语句返回的数据。然后尝试在新语句中使用顶级linq查询中的别名c。我会把它们合并成一个声明 假设LocationID是SelectList,请尝试以下操作:
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());
我自己没有运行这个,所以请仔细检查代码。您也可以在此处看到更多信息:我收到一条错误消息“SelectList”不包含接受0参数的构造函数。我感觉我有一些语法错误。我修改了答案来修正。它应该适合您。我收到一个错误,当前上下文中不存在名称“a”。请将a更改为d。我刚从你的原始帖子中删除了,所以我错过了别名的更改。我收到一个错误SelectListItem“不包含”的定义ToList什么是通信类型?请将类型添加到您的问题中。LocationID也一样。@GertArnold我用你问题的答案更新了描述。你明白为什么不能给它分配数据吗?此外,DeptText在通信实例中的位置如何?@GertArnold我最终要做的是从数据库中提取结果,允许用户更新任何不正确的值。我想做的是有一个选择下拉框,显示数据库中的选定值以及列表中的其他值。CommDept表中的字段CommDeptID和DeptText中有值,如1 HR、2 Administration、3 it等。LocationID等于CommDeptID。您是用C编程的。这要求您对类、类型实例、类型安全性等有最低限度的了解。我决不想粗鲁,但如果您不了解基本知识,在堆栈溢出时提问肯定是徒劳的。我不知道如何进一步指导你,因为你似乎不理解我的两个简单问题。