tags:

views:

31

answers:

2

When I want to Insert data in my table this Exception appeared

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Message_Subject". The conflict occurred in database "C:\DOCUMENTS AND SETTINGS\TEHRANI\DESKTOP\MESSAGEADMINPAGE\APP_DATA\ASPNETDB.MDF", table "dbo.Subject", column 'ID_Subject'. The statement has been terminated.

This Code for Insert :

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

you must set value all of feild

           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;
            }
mohammad reza
so I presume your value of ID_Subject in your original code was null, that's why you were getting duplicate values, correct?
Nathan Koop
where do I presume my value of ID_Subject null?this code work correct
mohammad reza
A: 

For what I can tell, based in the FOREIGN KEY constraint "FK_Message_Subject", you also have a table to Subjects. If this assumption is correct, when you assign M.ID_Subject a new Guid, it might not exist as a FOREIGN KEY in the Subjects table. You must find any existing Subject with the SubjectDDL.SelectedValue and retrieve the existing ID for the FOREIGN KEY. If it doesn't exist, create a new Subject and assign it directly to the Message M.

The same applies to when SubjectDDL.SelectedItem.ToString() == "Other". In this case, the FOREIGN KEY is null and it might be causing this error also.

bruno conde