我有 2 张桌子:tbleducation 和 tblemployee。tblemployee 表有诸如:employeeID、employeeName 等字段,而 tbleducation 有诸如:Id、employeeID 等字段。
我想创建一个下拉列表,从 tblemployee 表中选择一个给定employeeName 的employeeID,以便将其插入到tbleducation 中。我编写的代码如下:
模型
public class UserModels
{
public string EmployeeName { get; set; }
public int EmployeeCode { get; set; }
public IEnumerable<SelectListItem> Employee { set; get; }
}
控制器
[HttpPost]
public ActionResult Education(FormCollection edu)
{
tblEmployee_Education education = new tblEmployee_Education();
education.EmployeeID = Convert.ToInt32(edu["EmployeeName"].ToString());
education.Duration = edu["Duration"].ToString();
education.Certificate = edu["Certificate"].ToString();
education.Country = edu["Country"].ToString();
education.SchoolName = edu["SchoolName"].ToString();
education.Major = edu["Major"].ToString();
education.SubDescript = edu["SubDescript"].ToString();
context.AddTotblEmployee_Education(education);
context.SaveChanges();
return View();
}
看法
<%= Html.DropDownListFor(x => x.EmployeeName, Model.Employee, "select EmployeeName")%>
当我尝试插入时,我收到以下错误消息:
“INSERT 语句与 FOREIGN KEY 约束 FK_tblEmployee_Education_tblEmployee_Employee 冲突”。冲突发生在数据库“MP_DBS_old”、表“dbo.tblEmployee_Employee”、列“代码”中。该语句已终止。”
我知道发生此错误是因为下拉列表中的值是一个字符串,并且数据库需要一个整数(employeeID)。我真的不知道如何解决它。请任何人帮助我!