【问题标题】:Transfer repository data to MVC Model将存储库数据传输到 MVC 模型
【发布时间】:2011-08-20 13:46:08
【问题描述】:

我收到一个错误

错误 826 无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“OVR.Models.ChildInfoModel”。存在显式转换(您是否缺少演员表?) C:\dev.....\Controllers\NewRecordController.cs 129 34 OVR

    public ActionResult ChildInfo(ChildInfoModel childInfoModel)
    {
        //INewRecord newRecord = (INewRecord)TempData["newRecord"];

        if (TempData["CertNum"].ToString() == "")
        {
            return View();
        }
        else
        {
            string certNum = (string)TempData["CertNum"];

            //call up Child Info Screen
            var repo = new Get_Home_Repository();
            childInfoModel = repo.Get_Screen_DataDS(certNum, "ChildInfo");
            //childInfoModel = cModel;

            return View(childInfoModel);
        }

    }
  1. TempData["CertNum"] 包含我需要的值
  2. 使用@model OVR.Models.ChildInfoModel 为模型强类型化视图
  3. 我在参数中添加了 (ChildInfoModel childInfoModel),但如果未单击链接,则将拉出空白页面并允许填写,否则我传入从存储库中提取数据所需的参数,然后填充接口 IChildInfo,其中包含来自列表的数据作为 IEnumerable。我想我可以以某种方式显式转换 .. 或者接口 IChildInfo 需要更新才能将模型传回视图。如何从存储库数据中填充模型?

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    Get_Screen_DataDS 返回什么?方法签名返回什么?看来您正在从 Get_Screen_DS 返回 IEnumerable - 这是什么 IEnumerable? 您正在分配给 childInfoModel 的实例,我假设它不是 IEnumerable 但我无法从您发布的内容中真正看出。

    您应该返回一个 IEnumerable 吗?如果 ChildInfoModel 实现 IEnumerable 则只需简单地转换它

    childInfoModel = (ChildInfoModel) repo.Get_Screen_DataDS(certNum, "ChildInfo"); 但是在这种情况下,您可能应该只设置 Get_Screen_DataDS 返回类型 ChildInfoModel。

    此外,从长远来看,坚持一致和标准的 .net 命名约定对您有很大帮助。

    var repo 将是 var 存储库。 GetScreenDataDS 将是.... GetScreenData() 或 GetScreenDataByCert() FxCop 规则可以帮助您:) 只是我的额外 .00000002

    【讨论】:

    • 命名部分是由另一个开发人员完成的......无论如何签名是:public IEnumerable Get_Screen_DataDS(string pCert, string pScreen) 然后模型签名是:public class ChildInfoModel : IChildInfo 这个不允许使用实体框架的 Oracle 9 正在杀死我。在没有 EF 的情况下做 MVC 让我发疯。我会在上面尝试您的解决方案。希望这些签名能让您更好地了解正在发生的事情。是的,您现在让我考虑返回 ChildInfoModel,请再次告诉我您对此的想法。提前致谢。
    • InvalidCastException ... 无法将“System.Collections.Generic.List`1[OVR.DAL.IChildInfo]”类型的对象转换为“OVR.Models.ChildInfoModel”类型。当这条线被击中时 childInfoModel = (ChildInfoModel)repo.Get_Screen_DataDS(certNum, "ChildInfo");
    • 你不能这样做。您正在尝试将 GetScreenDataDS 中的项目列表分配给单个项目(您的模型)。您需要将模型更改为列表类型或更改 GetScreenDataDS 返回的内容。如果您的页面是 ChildInfoModel 的强类型,而不是 IEnumerable 那么您尤其不能将列表发送到您的视图,只能发送一个对象。
    • 我正在尝试将带有 lambda 表达式的数据集传递到我的 ChildInfo 属性类中,1。可以这样做吗? 2. 我最终在这里发布了有关数据集/lambda 表达式的问题,非常感谢任何帮助。 stackoverflow.com/questions/7134624/…
    • 不,您不能自动将数据集转换为模型。您需要将第一个数据集行中的列分配给您的模型。
    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    相关资源
    最近更新 更多