INSERT语句与FOREIGN KEY约束“fk_JOB_POSTING_CLIENT”冲突。冲突发生在数据库“ResLand”,表“dbo.CLIENT”,列“ID”中。声明已经终止。
当我在作业发布屏幕中插入数据时,我收到了上述异常消息 我对job_posting表的数据库设计是:
INSERT INTO [dbo].[JOB_POSTING]
([COMP_ID]
,[RES_ID]
,[RES_TYPE]
,[CONTACT_NAME]
,[CONTACT_INFO]
,[TITLE]
,[DESCR]
,[PREREQUISITES]
,[SKILLS]
,[JOB_TYPE]
,[LOCATION]
,[DURATION]
,[POST_DT]
,[POST_END_DT]
,[POSITIONS_CNT]
,[CLIENT_ID]
,[CATEGORY]
,[RATE]
,[PERKS]
,[STAT]
,[IS_DELETED]
,[CR_BY]
,[DT_CR]
,[MOD_BY]
,[DT_MOD])
在我的控制器中我写了这样的代码:
[ValidateInput(false)]
//[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult PostJob(PostJobModel model, string btn)
{
if (btn == "Save")
{
JOB_POSTING jobPost = new JOB_POSTING();
jobPost.RES_ID = RL_Constants.RES_ID;
jobPost.RES_TYPE = RL_Constants.RES_TYPE;
jobPost.COMP_ID = RL_Constants.COMP_ID;
jobPost.POST_DT = Convert.ToDateTime(model.POST_DT);
jobPost.POST_END_DT = Convert.ToDateTime(model.POST_END_DT);
jobPost.POSITIONS_CNT = Convert.ToInt32(model.POSITIONS_CNTS);
jobPost.JOB_TYPE =Convert.ToString(model.JOB_TYPE);
jobPost.DURATION = model.DURATION;
jobPost.CATEGORY = Convert.ToString(model.CATEGORY_ID);
jobPost.PREREQUISITES = model.PREREQUISITES;
jobPost.LOCATION = model.LOCATION;
jobPost.RATE = model.RATE;
//CLIENT=model.CLIENT_ID
//CLIENT_ID=(model.CLIENT_ID)
jobPost.TITLE = model.POST_TITLE;
jobPost.DESCR = Regex.Replace(model.DESCRIPTION, @"<[^>]+>| ", "");
jobPost.CONTACT_NAME = model.CONTACT_PERSON;
jobPost.CONTACT_INFO = model.CONTACT_PHONE + "/" + model.CONTACT_EMAIL;
jobPost.SKILLS = model.SKILLS;
jobPost.PERKS = model.PERKS;
jobPost.DT_CR = DateTime.Now;
jobPost.CR_BY = RL_Constants.USER_NAME;
jobPost.STAT = "ACTIVE";
jobPost.IS_DELETED = "N";
reslandentity.JOB_POSTING.Add(jobPost);
reslandentity.SaveChanges();
}
return RedirectToAction("JobSearchList", "Employer");
}
问题在哪里
答案 0 :(得分:0)
错误消息显示您正在使用的客户端ID不存在于Client表中。你正确设置cliendId fk引用吗?在您发布的代码中,clientId的设置已被注释掉。这意味着clientId = 0(如果它是一个int),我打赌你没有任何id = 0的客户。
----更新----- 当您的clientId = 0时,它会尝试与客户端表建立fk关系,但这会失败。你说你此时并不想使用clientId,而且clientId列可以为空。我不确定为什么它会分配0值,但只是为了检查它是否有效,你应该在映射中执行clientId = null。这应该可以防止EF尝试建立fk关系。