【问题标题】:passing record to a view using entity framework使用实体框架将记录传递给视图
【发布时间】:2011-12-07 11:19:09
【问题描述】:

我正在使用 .NET 4.0、MVC3 和实体框架 4.0

我需要将“语句”类型的数据库记录传递给视图。获取记录的代码如下:

public ActionResult pdfStatement(string InvoiceNumber)

{

            ObjectParameter[] parameters = new ObjectParameter[1];

            parameters[0] = new ObjectParameter("InvoiceNumber", InvoiceNumber);

            return View(_db.ExecuteFunction<Models.Statement>("uspInvoiceStatement", parameters));            
        }

“uspInvoiceStatement”是我用来获取“statement”的存储过程

我创建了一个接收“语句”的强类型视图

< % @ Page Language="C#" Inherits="System.Web.Mvc.ViewPage < InvoiceSearch.Models.Statement >" %>

当我运行应用程序时,我得到一个异常提示

    "The model item passed into the dictionary is of type 'System.Data.Objects.ObjectResult`1[InvoiceSearch.Models.Statement]',
 but this dictionary requires a model item of type 'InvoiceSearch.Models.Statement'. 

帮助我摆脱这个麻烦。 "

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 entity-framework


    【解决方案1】:

    该错误非常有用 - 它告诉您,您正在将 ObjectResult 发送到视图 asi viewmodel,而您应该发送 Statement。

    您的 _db.ExecuteFunction 总是返回 ObjectResult,因此您需要从中获取 Statement,如下所示:

    var statementResult = _db.ExecuteFunction<Models.Statement>("uspInvoiceStatement", parameters);
    var statement = statementResult.SingleOrDefault();
    if (statement != null)
    {
        return View(statement); // isnt that nicer when you can see what your viewmodel is?
    }
    else
    {
        return View("NotFound");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多