c#db相关代码中的神秘约束违规

时间:2010-12-09 10:20:10

标签: c# exception constraints

我使用存储过程从db(ms sql 2008 r2 express)获取数据。源表中的两个字段可能包含NULL值,因此当我在数据库设计器的VS中向我的项目添加数据源时,我将可空字段的AllowDBNull属性设置为True,将NullValue属性设置为(Empty)(两者都是字符串字段)。

尽管所有这些操作我每次生成datatadapter尝试获取具有空值的行时都会获得异常。我检查了所有内容:AllowDBNull为True,NullValue为(Empty),表中没有唯一键。

我的代码到底出了什么问题?

UPD“异常消息:无法启用约束。一行或多行包含值 违反非空,唯一或外键约束。“

代码:

foreach (BusStationDataSet.selectCarrierListRow row in _tblSource.Rows)
                    {
//Next line of code throws exception
                        BusStationDataSet.selectCarrierPhonesDataTable _tblPhones = _taPhones.GetData(row.carrierId, Settings.Default.DataLanguage);
                        phones = string.Empty;
                        int i = 0;

                        foreach (BusStationDataSet.selectCarrierPhonesRow phoneRow in _tblPhones.Rows)
                        {
                            i++;
                            string end = i == _tblPhones.Rows.Count ? "" : ", ";

                            phones += (phoneRow.countryCode != string.Empty ? phoneRow.countryCode : "") + (phoneRow.regionCode != string.Empty ? " (" + phoneRow.regionCode + ") " : "") + phoneRow.number +
                                end;
                        }
                        phones = phones == string.Empty ? MultilangInterface.Instance.GetMessageString(MultilangInterface.Messages.NullValue) : phones;

                        _dsDestination.Tables["Carrier"].Rows.Add(new object[]{
                            null,
                            row.carrierId,
                            row.title,
                            row.carrierType,
                            row.country,
                            row.city,
                            row.country + ", " + row.region + ", " + row.city + ", " + row.street + ", " + row.building + (string.IsNullOrEmpty(row.addressLine)?"":", " + row.addressLine),
                            row.lastName +" "+ row.firstName +" "+ row.middleName,
                            phones
                        });
                    }

1 个答案:

答案 0 :(得分:0)

最后我发现了这个问题。项目数据集中有两个生成的表,其名称几乎相似:selectCarriersPhonesDataTableselectCarrierPhonesDataTable。第二个是异常源,因为对于两个可空字段,NullValue属性都设置为(Throw Exception)。在我摆脱了这种取消后,一切都变得完美无瑕。我肯定应该睡个好觉:))