[英]A random exception is sometimes thrown whenever i add a record using entityframework
Hello so i have a working simple department database wherein the admin can add records( the only functionality that i have right now). 您好,所以我有一个工作简单的部门数据库,管理员可以在其中添加记录(我现在拥有的唯一功能)。
Here are my essential codes: 这是我的基本代码:
Context class: 上下文类:
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; }
}
Controller class: 控制器类:
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();
}
}
My views are just the default templates for create
and list
我的视图只是用于create
和list
的默认模板
My problem is that : They work as intended but sometimes, an exception will be thrown and will state that i failed to add my record(this is within my catch statement). 我的问题是:它们按预期工作,但有时会引发异常,并声明我无法添加记录(这在我的catch语句中)。 So i am not sure if it the error is from my code/structure or from my server itself. 所以我不确定是我的代码/结构还是服务器本身带来的错误。 What should i do? 我该怎么办?
edit: I was trying to trigger the error again but it wasn't showing up, i was testing my application earlier and sometimes my catch statement gets executed and i can't add any records after that. 编辑:我试图再次触发该错误,但没有出现,我在更早地测试我的应用程序,有时我的catch语句被执行了,此后我无法添加任何记录。 The error is entity dll error. 该错误是实体dll错误。 I will update once i found it out. 我一发现就会更新。
Pass department as an integer object to the Employee data object. 将部门作为整数对象传递给Employee数据对象。
int departmentID = 0;
departmentID = Convert.ToInt32(form["department"])
Employee entry = new Employee()
{
firstname = form["firstname"],
lastname = form["lastname"],
department = departmentID
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.