2016-05-02 5 views
2

Я работаю над проектом, в котором десериализуем XML и сопоставляем его с XML в базе данных, и он отлично работает, пока не дойдет до чужого столбца.Невозможно вставить в базу данных из-за ограничений внешнего ключа

У меня есть куча личной информации разных людей по XML, и я хочу прочитать их в базе данных. Существует только один тег, который не работает, и причина в том, что это внешний ключ.

Я получаю сообщение об ошибке:

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Seamen_UnregistrationReason". The conflict occurred in database "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. Я получаю ошибку при попытке вставить UnregistrationReason, когда нет такого столбца в XML, где я десериализую. Если это так, нужно просто пропустить его и двигаться дальше, но вместо этого я получаю эту ошибку.

Можно указать UnregistrationReason ЕСЛИ все лица имеют UnregistrationReason в своей личной информации, но в этом случае не все это делает, и я хочу, чтобы он просто пропустил его, если этот человек отсутствует на этой информации.

Моей целью: Я хочу код, чтобы пропустить UnregistrationReason при десериализации и вставок в базу данных если нет такого значения в XML.

Надеюсь, вы поняли, чего я хочу достичь, и, пожалуйста, спросите меня, есть ли у вас какие-либо вопросы.

+0

Что произойдет, если вы просто пропустить строку _command1.Parameters.AddWithValue ("@ UnregistrationReason", p.UnregistrationReason ?? DBNull.Value.ToString()); _ когда _UnregistrationReason_ равна нулю? – Marcus

ответ

0

Вы можете оставить 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()); 
+0

Спасибо, я думаю, что это может сработать.Однако, как видите, у меня есть 'SqlCommand command1 = new SqlCommand (query)' Как я могу добавить, если условие истинно? –

+1

Большое вам спасибо, это сработало. –

0

Попробуйте это:

Сначала убедитесь, что столбец таблицы принимает нулевые значения.

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

В противном случае устранить ограничение внешнего ключа.

Смежные вопросы