由于外键约束,无法插入数据库

时间:2016-05-02 09:41:39

标签: c# sql-server deserialization

我正在开发一个项目,在这个项目中反序列化XML并将其映射到XML到数据库,并且它可以完美地运行,直到它涉及到外来列。

我在XML上有一堆不同人的个人信息,我想将这些信息读到数据库中。只有一个标签不起作用,原因是它是一个外键。

我收到错误:

  

UPDATE语句与FOREIGN KEY约束冲突   " FK_Seamen_UnregistrationReason&#34 ;.冲突发生在数据库中   " Bums",table" dbo.UnregistrationReason",column' Code'。

以下是我使用的代码:

这里我反序列化XML

  List<FolkbokforingspostTYPE> deserializedList = new List<FolkbokforingspostTYPE>();
    deserializedList = Deserialize<List<FolkbokforingspostTYPE>>();

    var myPersons = Deserialize<List<FolkbokforingspostTYPE>>()
        .Select(x => new Person
        {
            PersonalIdentityNumber = x.Personpost.PersonId.PersonNr,
            SpecialIdentityNumber = x.Personpost.PersonId.Tilltalsnamnsmarkering != null ? x.Personpost.PersonId.Tilltalsnamnsmarkering : null, 
            LastName = x.Personpost.Namn.Efternamn,
            FirstName = x.Personpost.Namn.Fornamn,
            NationalRegistrationCountyCode = x.Personpost.Folkbokforing.LanKod,
            NationalRegistrationMunicipalityCode = x.Personpost.Folkbokforing.KommunKod,
            NationalRegistrationDistributionAddress1 = x.Personpost.Adresser.Folkbokforingsadress != null ? x.Personpost.Adresser.Folkbokforingsadress.Utdelningsadress1 : null,
            NationalRegistrationDistributionAddress2 = x.Personpost.Adresser.Folkbokforingsadress != null ? x.Personpost.Adresser.Folkbokforingsadress.Utdelningsadress2 : null,
            NationalRegistrationPostCode = x.Personpost.Adresser.Folkbokforingsadress != null ? x.Personpost.Adresser.Folkbokforingsadress.PostNr : null,

            UnregistrationReason = x.Personpost.Avregistrering != null ? x.Personpost.Avregistrering.AvregistreringsorsakKod : null,
            UnregistrationDate = x.Personpost.Avregistrering != null ? x.Personpost.Avregistrering.Avregistreringsdatum : null,

            NationalRegistrationCity = x.Personpost.Adresser.Folkbokforingsadress != null ? x.Personpost.Adresser.Folkbokforingsadress.Postort : null,
            BirthCountyCode = x.Personpost.Fodelse.HemortSverige != null ? x.Personpost.Fodelse.HemortSverige.FodelselanKod : null,
            BirthParish = x.Personpost.Fodelse.HemortSverige != null ? x.Personpost.Fodelse.HemortSverige.Fodelseforsamling : null,
            CitizenshipDate = x.Personpost.Medborgarskap != null ? x.Personpost.Medborgarskap.Medborgarskapsdatum : null,

            CitizenshipCode = x.Personpost.Medborgarskap.MedborgarskapslandKod,

            // and so on
        });

我在这里将其读入数据库

string connetionString = null;


        SqlDataAdapter adpter = new SqlDataAdapter();
        DataSet ds = new DataSet();
        XmlReader xmlFile;



        connetionString = "Data Source=tsrv2062;Initial Catalog=Bums;User ID=BumsUser;Password=2tusen7Bums";


        xmlFile = XmlReader.Create("navetout.xml", new XmlReaderSettings());
        ds.ReadXml(xmlFile);


        using (var connection = new SqlConnection(connetionString))
        {
            connection.Open();



            DateTime datum = DateTime.Now;

            SqlCommand command1 = new SqlCommand("UPDATE Seamen SET FirstName = @FirstName, LastName = @LastName, NationalRegistrationCountyCode = @NationalRegistrationCountyCode, NationalRegistrationMunicipalityCode = @NationalRegistrationMunicipalityCode, NationalRegistrationDistributionAddress1 = @NationalRegistrationDistributionAddress1, NationalRegistrationDistributionAddress2 = @NationalRegistrationDistributionAddress2, UnregistrationReason = @UnregistrationReason, UnregistrationDate = @UnregistrationDate, NationalRegistrationPostCode = @NationalRegistrationPostCode,NationalRegistrationCity = @NationalRegistrationCity, BirthCountyCode = @BirthCountyCode, BirthParish = @BirthParish, CitizenshipCode = @CitizenshipCode, LastChangedDate = @LastChangedDate WHERE PersonalIdentityNumber = @PersonalIdentityNumber", connection);

            foreach (Person p in myPersons)
            {

                command1.Parameters.Clear();
                command1.Parameters.AddWithValue("@PersonalIdentityNumber", string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
                command1.Parameters.AddWithValue("@FirstName", p.FirstName);
                command1.Parameters.AddWithValue("@LastName", p.LastName);
                command1.Parameters.AddWithValue("@NationalRegistrationCountyCode", p.NationalRegistrationCountyCode);
                command1.Parameters.AddWithValue("@NationalRegistrationMunicipalityCode", p.NationalRegistrationMunicipalityCode);
                command1.Parameters.AddWithValue("@NationalRegistrationDistributionAddress1", p.NationalRegistrationDistributionAddress1 ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@NationalRegistrationDistributionAddress2", p.NationalRegistrationDistributionAddress2 ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@NationalRegistrationPostCode", p.NationalRegistrationPostCode ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@NationalRegistrationCity", p.NationalRegistrationCity ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@BirthCountyCode", p.BirthCountyCode ?? DBNull.Value.ToString());

                command1.Parameters.AddWithValue("@UnregistrationReason", p.UnregistrationReason ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@UnregistrationDate", p.UnregistrationDate ?? DBNull.Value.ToString());

                command1.Parameters.AddWithValue("@BirthParish", p.BirthParish ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@CitizenshipCode", p.CitizenshipCode);
                command1.Parameters.AddWithValue("@CitizenshipDate", p.CitizenshipDate ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@LastChangedDate", datum);



                command1.ExecuteNonQuery();

                Console.WriteLine(string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));


            }
        }

        Console.WriteLine("Done");


        }// Put a break-point here, then mouse-over PersonalIdentityNumber...  deserializedList contains everything if you need it
       catch (Exception)
        {

            throw;
        }
        Console.ReadKey();
    }

这里我得到错误: command1.Parameters.AddWithValue("@UnregistrationReason", p.UnregistrationReason ?? DBNull.Value.ToString());

这是我的类来存储值

class Person {
       public string PersonalIdentityNumber { get; set; }
       public string SpecialIdentityNumber { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string NationalRegistrationCountyCode { get; set; }
       public string NationalRegistrationMunicipalityCode { get; set; }
       public string NationalRegistrationDistributionAddress1 { get; set; }
       public string NationalRegistrationDistributionAddress2 { get; set; }
       public string NationalRegistrationPostCode { get; set; }
       public string NationalRegistrationCity { get; set; }
       public string BirthCountyCode { get; set; }
       public string BirthParish { get; set; }
       public string CitizenshipDate { get; set; }
       public string UnregistrationReason { get; set; }
       public string UnregistrationDate { get; set; }
       public string CitizenshipCode { get; set; }
}

正如我所说,在包含作为外键的列UnregistrationReason之前,这曾经工作过。

我正在将多个人的个人信息读入数据库。并非所有人都有UnregistrationReason。当我在我反序列化的XML中没有这样的列时,尝试插入UnregistrationReason时出现错误。如果是这种情况,它应该跳过它继续前进,但我得到了那个错误。

可以包括UnregistrationReason如果所有人都有UnregistrationReason的个人信息,但在这种情况下并非所有人都这样做,我希望它只是跳过它,如果那个人失踪了关于那些信息。

我的目标:我希望代码在反序列化和插入数据库时​​跳过UnregistrationReason 如果,XML中没有这样的值。< / p>

我希望你理解我想要达到的目标,如果你有任何问题,请问我。

2 个答案:

答案 0 :(得分:0)

试试这个:

首先确保表列接受空值。

if(!string.IsNullOrEmpty(p.UnregistrationReason))
    command1.Parameters.AddWithValue("@UnregistrationReason", p.UnregistrationReason);

否则,删除外键约束。

答案 1 :(得分:0)

如果您没有SQL查询,或者不想更新它,可以将UnregistrationReason保留在SQL查询之外。例如:

String sql="UPDATE Seamen SET FirstName = @FirstName, LastName = @LastName, NationalRegistrationCountyCode = @NationalRegistrationCountyCode, NationalRegistrationMunicipalityCode = @NationalRegistrationMunicipalityCode, NationalRegistrationDistributionAddress1 = @NationalRegistrationDistributionAddress1, NationalRegistrationDistributionAddress2 = @NationalRegistrationDistributionAddress2, UnregistrationDate = @UnregistrationDate, NationalRegistrationPostCode = @NationalRegistrationPostCode,NationalRegistrationCity = @NationalRegistrationCity, BirthCountyCode = @BirthCountyCode, BirthParish = @BirthParish, CitizenshipCode = @CitizenshipCode, LastChangedDate = @LastChangedDate";

if(HaveUnregistrationReason)
    sql += ", UnregistrationReason = @UnregistrationReason";
sql += " WHERE PersonalIdentityNumber = @PersonalIdentityNumber";
SqlCommand command1 = new SqlCommand(sql, connection);

if(HaveUnregistrationReason)
    command1.Parameters.AddWithValue("@UnregistrationReason", p.UnregistrationReason ?? DBNull.Value.ToString());