我使用的是.NET 4.0和SQL Server 2008 R2。
我有三张桌子:
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);
}
}
答案 0 :(得分: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