当我使用entityframework添加记录时,有时会抛出随机异常

本文关键字:异常 随机 entityframework 添加 加记录 | 更新日期: 2023-09-27 18:09:19

你好,所以我有一个工作简单的部门数据库,其中管理员可以添加记录(我现在唯一的功能)。

以下是我的基本代码:

上下文类:

public class DepartmentController : Controller
{
    public ActionResult Index()
    {
        EmployeeContext emp = new EmployeeContext();
       List<Department> aDep =  emp.Departments.ToList();
        return View(aDep);
    }
}

Employee Model class:

[Table("carl")]
public class Employee
{

    public int id { get; set; }
    [DisplayName("First Name")]
    [Required(ErrorMessage = "First name is required")]
    public string firstname { get; set; }

    [DisplayName("Last name")]
    [Required(ErrorMessage = "Last name is required")]
    public string lastname { get; set; }

    [DisplayName("Department")]
    [Range(1, 3)]
    [Required(ErrorMessage = "Dep num is required")]
    public int department { get; set; }

}

控制器类:

public class HomeController : Controller
{
    //
    // GET: /Home/
    public ActionResult Index()
    {           
        EmployeeContext emp = new EmployeeContext();
        List<Employee> adep = emp.Employees.ToList();
        return View(adep);
    }

    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Create(FormCollection form)      
    {
        if (ModelState.IsValid)
        {
            try
            {
                EmployeeContext emp = new EmployeeContext();
                Employee entry = new Employee()
                {
                    firstname = form["firstname"],
                    lastname = form["lastname"],
                    department = Convert.ToInt32(form["department"])
                };
                emp.Employees.Add(entry);
                emp.SaveChanges();
            }
            catch (Exception e)
            {
                Response.Write("Failed to Add, please try again");
            }
        }      
        return View();
    }
}

我的视图只是createlist的默认模板

我的问题是:它们按预期工作,但有时会抛出一个异常,并将声明我未能添加我的记录(这是在我的catch语句中)。所以我不确定如果它的错误是从我的代码/结构或从我的服务器本身。我该怎么办?

编辑:我试图再次触发错误,但它没有出现,我在早些时候测试我的应用程序,有时我的catch语句被执行,之后我不能添加任何记录。错误是实体dll错误。我一找到就更新

当我使用entityframework添加记录时,有时会抛出随机异常

将department作为整数对象传递给Employee数据对象。

int departmentID = 0;
departmentID = Convert.ToInt32(form["department"])
 Employee entry = new Employee()
                {
                    firstname = form["firstname"],
                    lastname = form["lastname"],
                    department = departmentID
                };