C# 如何使用实体框架获取记录列表错误-模型项已传递到字典中,但此字典需要模型项
如何使用实体框架获取表中的记录列表,im获取错误- 传递到字典中的模型项的类型为 “System.Data.Entity.DbSetC# 如何使用实体框架获取记录列表错误-模型项已传递到字典中,但此字典需要模型项,c#,entity-framework,C#,Entity Framework,如何使用实体框架获取表中的记录列表,im获取错误- 传递到字典中的模型项的类型为 “System.Data.Entity.DbSet1[SmartPondDataAccess.Alert]”,但是 字典需要类型为的模型项 'System.Collections.Generic.IEnumerable1[SmartPondDataAccess.AlertsViewModel]' 视图模型 public class AlertsViewModel { public in
1[SmartPondDataAccess.Alert]”,但是
字典需要类型为的模型项
'System.Collections.Generic.IEnumerable
1[SmartPondDataAccess.AlertsViewModel]'
视图模型
public class AlertsViewModel
{
public int Deviceid { get; set; }
public Nullable<decimal> LowDO1 { get; set; }
public Nullable<decimal> LowDO2 { get; set; }
}
看法
@model IEnumerable
@{
ViewBag.Title=“设置”;
Layout=“~/Views/Shared/\u Layout\u SmartPond.cshtml”;
}
名称
@foreach(模型中的var项目)
{
@项目.设备ID
}
您的页面需要使用哪种类型的IEnumerable
。因此您应该将警报
转换为警报模型
:
public ActionResult Settings() {
smartpondEntities entities = new smartpondEntities();
var alertList = entities.Alerts.ToList();
List<AlertsViewModel> alertViewModel = alertList.Select(s=> new AlertsViewModel()
{
Deviceid = //....
}).ToList();
return View(alertViewModel);
}
public ActionResult设置(){
smartpondEntities实体=新的smartpondEntities();
var alertList=entities.Alerts.ToList();
List alertViewModel=alertList.Select(s=>newalertsviewmodel()
{
Deviceid=/。。。。
}).ToList();
返回视图(alertViewModel);
}
是否尝试返回视图(entities.Alerts.ToList())代码>而不是返回视图(entities.Alerts)代码>?是,已尝试。同样的eror@SelimY阿尔兹是对的。此外,警报不是AlertsViewModelhow类型将其类型转换为AlertsViewModel,它应该返回AlertsViewModel列表。我添加了一个答案,请检查。
@model IEnumerable<SmartPondDataAccess.AlertsViewModel>
@{
ViewBag.Title = "Settings";
Layout = "~/Views/Shared/_Layout_SmartPond.cshtml";
}
<table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th style="width:150px">Name</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Deviceid </td>
</tr>
}
</tbody>
</table>
public ActionResult Settings() {
smartpondEntities entities = new smartpondEntities();
var alertList = entities.Alerts.ToList();
List<AlertsViewModel> alertViewModel = alertList.Select(s=> new AlertsViewModel()
{
Deviceid = //....
}).ToList();
return View(alertViewModel);
}