在Asp.net mvc5中查询

时间:2017-10-25 07:45:54

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

g++ mainMatrix.cpp 
In file included from mainMatrix.cpp:2:0:
Matrix.H:189:87: error: no ‘data_type& Matrix<N, M, data_type>::operator()(std::size_t, std::size_t)’ member function declared in class ‘Matrix<N, M, data_type>’
 inline data_type& Matrix<R,C,data_type>::operator()(std::size_t row, std::size_t col) noexcept {
                                                                                       ^~~~~~~~
Matrix.H:199:98: error: no ‘const data_type Matrix<N, M, data_type>::operator()(std::size_t, std::size_t) const’ member function declared in class ‘Matrix<N, M, data_type>’
 const data_type Matrix<R,C,data_type>::operator()(std::size_t row, std::size_t col) const noexcept {

我的员工表中有5列public ActionResult Index() { return View(db.Employees.Select(x => new { x.First_Name, x.Last_Name, x.Email }).ToList()); } First_NameLast_NameAddressSalary。在这5列中,我想在浏览器中仅显示EmailFirst_NameLast_Name。 这是我正在使用的视图

Email

我收到的错误是:在此期间生成了未处理的异常 执行当前的Web请求。可以使用下面的异常堆栈跟踪来识别有关异常的起源和位置的信息。

我是asp.net Mvc的初学者。我该怎么办?

2 个答案:

答案 0 :(得分:2)

您正在向视图发送匿名对象而不是Employee列表。

db.Employees.Select(x => new { x.First_Name, x.Last_Name, 
         x.Email })

由于您不希望显示更多您不希望显示的属性,因此不鼓励将域模型Employee直接发送到视图,我只会为您需要的信息创建view model

查看模型

public class EmployeeViewModel
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

控制器

public ActionResult Index()
{
    var vm = new List<EmployeeViewModel>();

    foreach (var employee in db.Employees)
    {
        vm.Add(new EmployeeViewModel
        {
            EmployeeId = employee.ID,
            FirstName = employee.First_Name,
            LastName = employee.Last_Name,
            Email = employee.Email
        });
    }

    return View(vm);
}

视图

@model IList<crudOperation.EmployeeViewModel>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<table>
    <thead>
        <tr>
            <th>First name</th>
            <th>Last name</th>
            <th>Email</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var employee in Model)
        {
            <tr>
               <td>@employee.FirstName</td>
               <td>@employee.LastName</td>
               <td>@employee.Email</td>
               <td>
                   @Html.ActionLink("Edit", "Edit", new { id= employee.EmployeeId }) |
                   @Html.ActionLink("Details", "Details", new { id= employee.EmployeeId }) |
                   @Html.ActionLink("Delete", "Delete", new { id= employee.EmployeeId })
               </td>
            </tr>
        }
    </tbody>
</table>

答案 1 :(得分:0)

您正在返回非Employee对象的集合。如果要返回List,可以使用_db.Employees.ToList(),否则必须创建一个包含要返回属性的DTO类。