简体   繁体   English

Mvc无效的操作异常

[英]Mvc Invalid operation exception

I need to retrieve employees from my-sql server database depending on the id parameter passed. 我需要根据传递的id参数从my-sql服务器数据库中检索员工。 For example: http://localhost:66666/employee/details/1 <---the parameter and match the parameter with an id in the database and display it in the view. 例如: http://localhost:66666/employee/details/1 <---the parameter ,并将参数与数据库中的ID匹配,并在视图中显示它。 For some reason I am getting an invalid operation exception on this line in the employee controller: Employee employee = EmployeeContext.Employees.Single(emp => emp.EmployeeID == id); 由于某种原因,我在雇员控制器的这一行上收到无效的操作异常: Employee employee = EmployeeContext.Employees.Single(emp => emp.EmployeeID == id);

I am not sure if the error actually originates there. 我不确定该错误是否真正起源于此。

employee controller 员工控制人

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTutorials.Models;

namespace MVCTutorials.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Details(int id)//id =paramenter 
        {

            EmployeeContext EmployeeContext = new EmployeeContext();

            Employee employee = EmployeeContext.Employees.Single(emp => emp.EmployeeID == id);
            return View(employee);

        }
    }
}

employee model 员工模式

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MVCTutorials.Models
{
    [Table("TblEmp")]
    public class Employee
    {
        [Key]
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
    }
}

employee view 员工观点

@model MVCTutorials.Models.Employee
@{
    ViewBag.Title = "Employeee Details";
}

<h2>Employeee Details</h2>

<table style="font-family:Arial;">
    <tr><!--The Row-->
        <td>
                <b>Employee Id: </b>
        </td>
        <td>
            @Model.EmployeeID
        </td> 
    </tr>
    <tr>
        <td>
            Name:
        </td>
        <td>
            @Model.Name
        </td>
    </tr>
    <tr>
        <td>Gender:</td>
        <td>@Model.Gender</td>
    </tr>
    <tr>
        <td>City:</td>
        <td>@Model.City </td>
    </tr>
</table>

Employee context 员工背景

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MVCTutorials.Models
{
    public  class EmployeeContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

Global.aspx Global.aspx

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MVCTutorials
{
    public class MvcApplication : System.Web.HttpApplication
    {
        //Happens when appplication first starts
        protected void Application_Start()
        {
            //Purpose used to initalize your database e.g if you dont have a database created already this will create one for you(database,tables and data will all be created)
            // we pass null saying we dont want any of this
            Database.SetInitializer<MVCTutorials.Models.EmployeeContext>(null);
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Single method Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence. 单个方法返回序列中的唯一元素,如果序列中不存在一个元素,则引发异常。 so you can use SingleOrDefault function which return null if you havnt any desired row. 因此您可以使用SingleOrDefault函数,如果您有任何所需的行,则该函数将返回null。

Employee employee = EmployeeContext.Employees.SingleOrDefault(emp => emp.EmployeeID == id);

According to the MSDN for Enumerable.Single() : 根据MSDN的Enumerable.Single()

InvalidOperationException The input sequence contains more than one element. InvalidOperationException输入序列包含多个元素。 -or- The input sequence is empty. -或者-输入序列为空。

I believe you have either more than one Employee or none who matches the criteria so exception is thrown. 我相信您要么有一个以上的雇员,要么没有一个符合条件的雇员,所以抛出了异常。

You should either use First() if it is possible that more than one Employee exists or use SingleOrDefault and check for null . 如果可能存在多个Employee ,则应该使用First() ,或者使用SingleOrDefault并检查null

Instead of using Single method, use Find and then verify if it was found. 而不是使用Single方法,而是使用“ Find ,然后验证是否已找到它。

Employee employee = EmployeeContext.Employees.Find(id);
if (employee == null)
    // not found on database 

As per documentation , Single method will success only if there is exaclty one record matching your criteria. 根据文档 ,仅当有一条符合您的条件的记录时, Single方法才会成功。 Not more not less than one record. 不少于一项记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM