当插入的数据适合时,为什么插入与FK约束冲突?

时间:2016-07-28 13:44:23

标签: c# sql-server

我正在将数据插入数据库的Receipts表中。此表与Stores.Id = Receipts.StoreId

上链接的商店有结构关系

有时,插入会遇到以下错误:

  

System.Data.SqlClient.SqlException:INSERT语句与FOREIGN KEY约束“FK_dbo.Receipts_dbo.Stores_StoreId”冲突。

我向数据库发了5000个帖子,这个错误在该批次中只发生了10次。所有5000个帖子的数据都是相同的(见下面的代码)。

修改

我已经运行了第二批5000个帖子,这一次所有这些帖子都没有错误地有效地发生错误发生的可能性1000:1

我已经确认Stores表中有一个商店,其中包含在ajax发布数据中指定的Id值。

有人能告诉我为什么我发送的帖子只有1/500遇到此错误?

// function gets the receipt number from the loop that calls it
function CreateData(receiptNumber) {
    var StoreId = 5;
    var ReceiptValue = 100.50;
    var Cashback = 10.50;

    var Receipt = {
        "StoreId": StoreId,
        "ReceiptNumber": receiptNumber,
        "ReceiptValue": ReceiptValue,
        "Cashback": Cashback };

    return Receipt;
}

// function initiates the loop for x times
function LoopPostData ( iterations ) {

    for ( var i = 1; i <= iterations; i++ ) {
        PostData( i );
    }
}

function PostData ( iteration ) {
    var PostCompleted = false,
        ReceiptNumber = "TST-"+ pad( iteration, 4 );

    UpdatePostsTable( "- Attempting to post "+ ReceiptNumber );

    $.ajax( {
        type: "post",
        url: "http://localhost:54354/api/Receipt",
        data: CreateData( ReceiptNumber ),
        success: function () {
            var msg = "-"+ ReceiptNumber +" was saved on the API";

            UpdateSuccessTable( msg ); // indicate the post was saved
        },
        statusCode: {
            400: function () {
                var msg = "-"+ ReceiptNumber +" was sent to API but not saved";

                UpdateErrorsTable( msg ); // indicate the post couldn't be saved

                PostCompleted = true;
            }
        },
        error: function () {
            if ( PostCompleted ) return;

            var msg = "-"+ ReceiptNumber +" was not sent to the API";

            UpdateErrorsTable( msg ); // indicate the post was sent to the API
        }
    } );
}

修改

以下是更多信息。

这是实际插入数据库的代码。它使用实体框架

private void PostReceipt(CreateReceiptViewModel Source)
{
    PocketPlootoEntities db = new PocketPlootoEntities();

    Receipt Receipt = new Receipt
    {
        Calculated = false,
        Cashback = Source.Cashback,
        Deleted = false,
        ReceiptDate = DateTime.Now,
        ReceiptNumber = Source.ReceiptNumber,
        ReceiptValue = Source.ReceiptValue,
        Redeemed = false,
        Store = db.Stores.FirstOrDefault(x => x.Id == Source.StoreId),
        StoreId = Source.StoreId,
        ValidUntil = DateTime.Now.AddDays(7)
    };

    db.Receipts.Add(Receipt);
    db.SaveChanges();
}

这是上面的ajax帖子。

这是Stores表(请记住,ajax使用Id 5(Roman's Pizza)发布到商店

Here's the Stores table

基于此,我无法相信错误正在发生,因为新收据的商店表中没有链接记录。

编辑2

我粘贴了实体框架Code-First用于创建表的POCO类以及用于创建表的SQL代码。

http://pastebin.com/7JDnbU2A

为节省一些时间,这是根据错误消息提出的外键约束:

ALTER TABLE [dbo].[Receipts]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Receipts_dbo.Stores_StoreId] FOREIGN KEY([StoreId])
REFERENCES [dbo].[Stores] ([Id])
ON DELETE CASCADE
GO

编辑3

我更新了我的服务器代码,只是为了让EF将其查询记录到Visual Studio中的输出窗口。

这是它执行的一个INSERT命令(该命令是随机选择的)

INSERT [dbo].[Receipts]([StoreId], [UserId], [ReceiptNumber], 
       [ReceiptValue], [ReceiptDate], [Cashback], [ValidUntil], 
       [Calculated], [Redeemed], [Deleted], [Invoice_Id])
VALUES (@0, NULL, @1, @2, @3, @4, @5, @6, @7, @8, NULL)
SELECT [Id]
FROM [dbo].[Receipts]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()


-- @0: '1' (Type = Int32)
-- @1: 'TST-0006' (Type = String, Size = -1)
-- @2: '100.5' (Type = Decimal, Precision = 18, Scale = 2)
-- @3: '2016/07/28 6:38:38 PM' (Type = DateTime2)
-- @4: '10.5' (Type = Decimal, Precision = 18, Scale = 2)
Opened connection at 2016/07/28 6:38:38 PM +02:00
-- @5: '2016/08/04 6:38:38 PM' (Type = DateTime2)
Started transaction at 2016/07/28 6:38:38 PM +02:00
-- @6: 'False' (Type = Boolean)
-- @7: 'False' (Type = Boolean)
-- @8: 'False' (Type = Boolean)

0 个答案:

没有答案