使用linqtosql时插入异常

时间:2009-10-13 12:51:19

标签: linq-to-sql

当我想在我的表格中插入数据时,此异常出现了

  

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();

2 个答案:

答案 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为空,也可能导致此错误。