【发布时间】:2018-11-28 08:24:14
【问题描述】:
我看过很多关于这个特定错误消息的帖子,但似乎没有一个能涵盖我的问题。错误是:'INSERT 语句与 FOREIGN KEY 约束冲突'
我已在名为 Tests 的表中将外键设置为 Null,因为并非每条记录都会在另一个名为 APIS 的表中具有相应的记录。
在 SSMS 中,我可以毫无问题地插入新记录,下面是我的 INSERT 查询。
INSERT INTO [dbo].[Tests]
([APIID]
,[ActiveID]
,[ABCDataID]
,[ReferenceNumber]
,[LocationAddress]
,[LocationPostCode]
,[Make]
,[Model]
,[Registration]
,[WPC]
,[IsA]
,[IsS]
,[SelfSetDate]
,[IsBA]
,[UserID]
,[ClaimAtFaultEnum]
,[ClaimADriverEnum]
,[XRepair]
,[ManRepair]
,[HybridRepair]
,[BodyType]
,[CustomerName]
,[CustomerEmail]
,[CustomerMobileNumber]
,[IsCancelled]
,[CancellationNote])
VALUES
(NULL,
NULL,
NUll,
'111111111',
'Waterside',
'KA18 8EX',
'Abarth',
'320',
'TIL1607',
NULL,
1,
0,
NULL,
0,
NUll,
1,
1,
0,
0,
0,
'Car',
'John Smith',
'John@TIL1607TestData.com',
'07test',
0,
Null)
GO
下面是我尝试使用 c# 放入数据库的相同数据,它似乎只在我设置外键时才有效。我不能放 NULL 因为它是一个 int 字段并且不会接受它,如果我完全忽略它,它会出现上面提到的错误消息。
Test testToAllocate = new Test();
if (testToAllocate != null)
{
int intClaimDriver = -1;
int intClaimAtFault = -1;
if (rdoDriverDriver.Checked)
{
intClaimDriver = (int)Enums.Test.Driver;
}
if (rdoNonDriver.Checked)
{
intClaimDriver = (int)Enums.Test.NonDriver;
}
if (rdoFaultFault.Checked)
{
intClaimAtFault = (int)Enums.Test.Fault;
}
if (rdoFaultNonFault.Checked)
{
intClaimAtFault = (int)Enums.Test.NonFault;
}
if (rdoFaultThirdParty.Checked)
{
intClaimAtFault = (int)Enums.Test.ThirdParty;
}
ABCData testToABC = db.AudaBridgeClaimDatas.Where(a => a.Registration == txtVehicleRegistration.Text).FirstOrDefault();
if (testToAllocate != null)
{
testToAllocate.ABCDataID = testToABC.ABCDataID;
}
else
{
testToAllocate.ABCDataID = null;
}
// testToAllocate.APIID = 5; //Needs to be Null
testToAllocate.ReferenceNumber = "111111111";
testToAllocate.LocationAddress = "Waterside";
testToAllocate.LocationPostCode = "KA18 8EX";
testToAllocate.Make = "Abarth";
testToAllocate.Model = "320";
testToAllocate.Registration = "TIL1607";
testToAllocate.IsA = true;
testToAllocate.IsS = false;
testToAllocate.IsBA = false;
testToAllocate.ClaimADriverEnum = 1;
testToAllocate.ClaimAtFaultEnum = 1;
testToAllocate.XRepair = false;
testToAllocate.ManRepair = false;
testToAllocate.HybridRepair = false;
testToAllocate.BodyType = "Car";
testToAllocate.CustomerName = "John Smith";
testToAllocate.CustomerEmail = "John@TIL1607TestData.com";
testToAllocate.CustomerMobileNumber = "07test";
testToAllocate.IsCancelled = false;
db.Claims.InsertOnSubmit(testToAllocate);
db.SubmitChanges();
有人有什么想法吗?就好像 Visual Studio 没有识别出我对数据库所做的更改以使该字段为空。
【问题讨论】:
-
在 db.submitchanges() 之前获取生成的 sql 代码,并与您的工作代码进行比较。
-
显示模型 - 类定义。