如何使用实体框架获取记录列表错误-传递到字典中的模型项,但此字典需要一个模型项



如何使用实体框架获取表中的记录列表,im geting error-

传递到字典中的模型项的类型为"System.Data.Entity.DbSet1[SmartPondDataAccess.Alert]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[SmartPondDataAccess.AlertsViewModel]".

查看模型

public class AlertsViewModel
{
public int Deviceid { get; set; }
public Nullable<decimal> LowDO1 { get; set; }
public Nullable<decimal> LowDO2 { get; set; }
}

c#代码

public ActionResult Settings() {
smartpondEntities entities = new smartpondEntities();
return View(entities.Alerts);
}

查看

@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>

您的页面需要IEnumerable<SmartPondDataAccess.AlertsViewModel>类型的模型。因此,您应该将Alerts转换为AlertVewModel:

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);
}