首页 > 解决方案 > 如何使用实体框架错误获取记录列表 - 模型项传递到字典中,但此字典需要模型项

问题描述

如何使用实体框架获取表中的记录列表,我收到错误 -

传递到字典中的模型项的类型为“System.Data.Entity.DbSet 1[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>

标签: c#entity-framework

解决方案


您的页面需要模型的类型。IEnumerable<SmartPondDataAccess.AlertsViewModel>所以您应该转换AlertsAlertVewModel

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

推荐阅读