0

我正在使用.NET 4.0和SQL Server 2008 R2。從強類型DataSet中刪除行後引發異常?

我有三個表:

Companies (PK CompanyID) 
Addresses (PK AddressID, FK CompanyID) 
ContactPersons (PK ContactPersonID, FK CompanyID) 

CompanyID是由用戶手動分配。其他ID是自動生成的。公司與ContactPerson有一對多的關係。我已設置任何更改級聯。

我在DataGridView的公司中顯示所有記錄,當單擊一行時,ContactPersons中的相應記錄顯示在第二個DataGridView中。

然後,我從表中ContactPersons與刪除行:

DataRow row = m_SoldaCompaniesFileDataSet.ContactPersons.Rows.Find(this.m_CurrentContactPerson.ContactPersonID); 
row.Delete(); 

當我嘗試查詢表創建一個數據源來填充的DataGridView:

var dataRows_ContactPersons = from row in this.m_SoldaCompaniesFileDataSet.ContactPersons 
           where row.CompanyID == companyID 
           select new 
           { 
           ContactPersonID = row.ContactPersonID, 
           CompanyID = row.CompanyID, 
           NameFirst = row.NameFirst, 
           NameLast = row.NameLast, 
           PhoneNumber = row.PhoneNumber, 
           EmailAddress = row.EmailAddress, 
           Position = row.Position 
           }; 

我收到DeletedRowInaccessibleException 。任何想法我在這裏做錯了嗎?

其實除了來自於自動生成的代碼類型化的DataSet:

[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] 
      public int CompanyID { 
       get { 
        try { 
         return ((int)(this[this.tableContactPersons.CompanyIDColumn])); // <<<--- DeletedRowInaccessibleException 
        } 
        catch (global::System.InvalidCastException e) { 
         throw new global::System.Data.StrongTypingException("The value for column \'CompanyID\' in table \'ContactPersons\' is DBNull.", e); 
        } 
       } 

回答

1

我已經後不久寫上面的問題(雖然我花了一天共)想通了:

var dataRows_ContactPersons = from row in this.m_SoldaCompaniesFileDataSet.ContactPersons 
           where row.RowState != DataRowState.Deleted && row.CompanyID == companyID 
           select new 
           { 
            ContactPersonID = row.ContactPersonID, 
            CompanyID = row.CompanyID, 
            NameFirst = row.NameFirst, 
            NameLast = row.NameLast, 
            PhoneNumber = row.PhoneNumber, 
            EmailAddress = row.EmailAddress, 
            Position = row.Position 
           }; 

有必要做這個檢查,以排除LINQ查詢刪除行:

row.RowState != DataRowState.Deleted 
相關問題