如何避免冲突FK与主表插入Linq到sql?

时间:2014-06-02 05:23:33

标签: c# mysql linq-to-sql

我编写了以下代码以插入到数据库中,以获取有关员工的信息。

我面对主表(员工)的多个FK表(语言,证书和DoctorType)的问题。

我有以下异常

  

INSERT语句与FOREIGN KEY约束冲突   " FK_certificates_staff&#34 ;.冲突发生在数据库中   " D:\ UNI \ CLINIK.MDF",table" dbo.staff",column' id'

我的代码:

public bool AddnewStaff(staff s , List<language> ln, List<certificate> cer, DoctorType dt)
   {
       using (DataClasses1DataContext ex = new DataClasses1DataContext())
       {
           try
           {
                // First insert Tables(lalanguage ,certificate , DoctorType ) that has FK to         staff table
                IEnumerable<language> lang = getAllLanguages(ln);
                IEnumerable<certificate> certificat = getAllCer(cer);
                ex.languages.InsertAllOnSubmit(lang); // insert list of languages
                ex.certificates.InsertAllOnSubmit(certificat); //insert list of certificates
                ex.DoctorTypes.InsertOnSubmit(dt);
                ex.SubmitChanges();

               //Now that those FKs are filled, we can insert the main entry with those FK values
               // now insert table staff 
                staff sa = new staff();
                sa = s;
                sa.certificates.Add((certificate)certificat);
                sa.languages.Add((language)lang);
                sa.DoctorTypes.Add(dt);
                ex.staffs.InsertOnSubmit(sa);
                ex.SubmitChanges();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }

    public IEnumerable<language> getAllLanguages(List<language> ln)
    {
        var lang = (IEnumerable<language>)ln;
        return lang;
    }

    public IEnumerable<certificate> getAllCer(List<certificate> cer)
    {
        // convert from list of certificate to IEnumerable<certificate> to use InsertAllOnSubmit method to insert into DB
        var c = (IEnumerable<certificate>)cer;
        return c;
    }
}

关于该做什么的任何想法?

0 个答案:

没有答案