c# - 如何使用实体框架错误获取记录列表 - 模型项传递到字典中,但此字典需要模型项
问题描述
如何使用实体框架获取表中的记录列表,我收到错误 -
传递到字典中的模型项的类型为“System.Data.Entity.DbSet
1[SmartPondDataAccess.Alert]', but this dictionary requires a model item of type '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; }
}
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);
}
推荐阅读
- python - 创建一个 numpy 数组的置换浅表副本
- python - 从 tkinter 中删除多个标签
- ios - 如何使用启动故事板或 XIB?
- flutter - 更改从外部类返回的抽屉小部件的抽屉图标
- python - 如何使用假设检验来比较组
- java - 无法在 ajax 覆盖弹出窗口中单击或发送键,并使用 selenium 和 java 显示 Element not Intractable 异常
- react-native - [未处理的承诺拒绝:TypeError:_reactNative.NativeModules.RNDatePickerAndroid.dismiss 不是函数
- python - 在postgresql表django中插入数据
- php - 如何保存函数的结果
- javascript - Fabric.js 逐像素操作 Image 对象以改变颜色