当我想在我的表格中插入数据时,此异常出现了
INSERT语句与FOREIGN KEY约束“FK_Message_Subject”冲突。冲突发生在数据库“C:\ DOCUMENTS AND SETTINGS \ TEHRANI \ DESKTOP \ MESSAGEADMINPAGE \ APP_DATA \ ASPNETDB.MDF”,表“dbo.Subject”,列'ID_Subject'中。 声明已经终止。
此插入代码:
string[] a = UserIDtxt.Text.Split(',');
foreach (String b in a)
{
Message M = new Message();
Guid i = (from q in MDB.aspnet_Memberships
where q.aspnet_User.UserName.ToString() == b.ToString()
select q).Single().UserId;
M.ID_Receiev = i;
M.ID_Message = Guid.NewGuid();
M.ID_Sender = (Guid)Admin.ProviderUserKey;
M.ID_Message_Parent = Guid.Empty;
if (SubjectDDL.SelectedItem.ToString() != "Other")
{
M.ID_Subject = new Guid(SubjectDDL.SelectedValue);
}
else
{
M.Other_Subject = Othertxt.Text;
}
M.Body = TEXTtxt.Text;
M.Date = DateTime.Now;
M.IsFinished = false;
M.IsRead = false;
MDB.Messages.InsertOnSubmit(M);
}
MDB.SubmitChanges();
答案 0 :(得分:0)
你必须设置所有字段的值
if (SubjectDDL.SelectedItem.ToString() != "Other")
{
M.ID_Subject = new Guid(SubjectDDL.SelectedValue);
M.Other_Subject = null;
}
else
{
M.ID_Subject = new Guid(SubjectDDL.SelectedValue);
M.Other_Subject = Othertxt.Text;
}
答案 1 :(得分:0)
据我所知,基于FOREIGN KEY constraint "FK_Message_Subject"
,您还有Subjects
的表格。如果此假设正确,则在为M.ID_Subject
分配新Guid
时,它可能不会作为Subjects
表中的FOREIGN KEY存在。您必须找到Subject
的任何现有SubjectDDL.SelectedValue
,并检索FOREIGN KEY的现有ID。如果它不存在,请创建一个新的Subject
并将其直接分配给Message M
。
这同样适用于SubjectDDL.SelectedItem.ToString() == "Other"
。在这种情况下,FOREIGN KEY为空,也可能导致此错误。