LINQ结果查看

时间:2014-11-14 02:51:47

标签: c# asp.net-mvc linq entity-framework razor

将LINQ查询的结果返回给视图的简单方法是什么?

我的控制器中有一个LINQ查询,它从数据库中获取结果,但在如何将其返回到视图方面却有点遗失。

控制器:

public ActionResult Index()
{
    if (Session["UserId"] == null)
    {
        return RedirectToAction("Index", "Login");
    }
    else
    {    
        EmployeeHomeViewModel model = new EmployeeHomeViewModel();

        var UserId = from x in db.Employees
                     where x.Employee_Id == Convert.ToInt32(Session["UserId"])
                     select x;

        //DISPLAY RESULT       

        var project = from x in db.Projects
                      where x.Employee_Id == Convert.ToInt32(Session["UserId"])
                      select x;
        foreach (Project result in project)
        {
            model.Project.Project_Id = result.Project_Id;
            model.Project.Project_Name = result.Project_Name;
            model.Project.Project_Detail = result.Project_Detail;             
        }

        //DISPLAY RESULT

    }

    return View();
}

查看:

@model ProjectManager.ViewModels.EmployeeHomeViewModel
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div>Hello, @Html.DisplayFor(model => model.Employee.Employee_FirstName)</div><br />
<div>Current project: @Html.DisplayFor(model => model.Project.Project_Id)</div><br />
<div>Project name: @Html.DisplayFor(model => model.Project.Project_Name)</div><br />
<div>Details: @Html.DisplayFor(model => model.Project.Project_Detail)</div><br />

型号:

public class EmployeeHomeViewModel
{
    public Employee Employee { get; set; }
    public Project Project { get; set; }        
}

编辑:

要清楚,在能够将LINQ查询的结果返回到视图之前,我必须修复在我的foreach循环中执行查询时发生的错误:

  

LINQ to Entities无法识别方法&#39; Int32 ToInt32(System.Object)&#39;方法,并且此方法无法转换为商店表达式

2 个答案:

答案 0 :(得分:1)

您应该将return View();替换为return View(model);

Controller.View method的几个重载可用于支持指定返回所需ViewResult所需的数量。在这种情况下,您需要Controller.View(Object)重载而不是无参数Controller.View()重载;前者的Object参数用于指定您希望作为返回的ViewResult基础的模型。

答案 1 :(得分:0)

  

我的foreach中出现了这个错误。

     

LINQ to Entities无法识别方法'Int32 ToInt32(System.Object)'方法,并且此方法无法转换为商店表达式

EF不直接支持Convert.ToInt32()方法。在你的情况下,它是一个简单的修复 - 只需将查询之外的会话变量转换(并重用它):

    int userID = Convert.ToInt32(Session["UserId"]);

    //DISPLAY RESULT       

    var project = from x in db.Projects
                  where x.Employee_Id == userID
                  select x;

我看到的其他一些事情:

  • 您根本没有使用UserId查询
  • 您正在迭代project查询的结果,但每次都会覆盖相同的值。我怀疑你的EmployeeHomeViewModel模型应该有项目的集合,而不是单个项目。