使用外键保存数据或回滚(如果有任何失败)

时间:2015-04-08 23:11:13

标签: c# sql linq

我有一个需要创建或更新一个表的Linq查询,然后获取id并填充另一个表。

示例:

public Batch SaveBatch(Batch batchModel, Audit auditModel)
{
    int batchID = 0;
    Batch batch;
    Audit audit = null;

    var exists = db.Batches.Where(t => t.BatchID == batchModel.BatchID);
    if (exists.Any())
    {
        batch = exists.First();
        batchID = batch.BatchID;

        if(batch.StatusID != 1) 
        {
           audit = CreateAudit(batchID, auditModel);
        }
        else
        {
           if (auditModel.EventTypeID == 16) 
           {
              audit = CreateAudit(batchID, auditModel);
           }
           else
           {
               var checkTrans = GetAllTransactions(batchModel.BatchID);
               if (checkTrans.Count() > 1)
               {
                   audit = CreateAudit(batchID, auditModel);
               }
           }
       }
    }
    else
    {
        batch = new Batch()
        {
            CreatedDate = batchModel.CreatedDate
        };

        db.Batches.InsertOnSubmit(batch);
        batchID = batch.BatchID;
        audit = CreateAudit(batchID, auditModel);
    }

    batch.Reason = batchModel.Reason;

    db.Audit.InsertOnSubmit(audit);
    db.SubmitChanges();
    return batch;
}

我收到错误,说外键不存在或不匹配。

我需要的是插入或更新表格批次,然后从批次插入或更新的记录中获取ID。使用BatchesID,我可以填充表Audit。

但是如果在插入表格中出现任何问题,它会回滚对表格批次所做的更改。

表审核包含Batches表的外键。

SQL表:

Batches

BatchesID | Reason | CreatedDate | ... 

Audit

AuditID | BatchesID | ...

1 个答案:

答案 0 :(得分:1)

如果您将保存包装在事务范围内,则当您保存更改时,您的批次将获得一个ID,您可以将其用于审计。如果事务内部出现任何故障,则所有内容都将回滚。 有关交易的详细信息,请参阅https://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v=vs.110).aspx,但请尝试以下操作:

using (TransactionScope scope = new TransactionScope())
{
if (exists.Any())
{
    batch = exists.First();
    batchID = batch.BatchID;

    if(batch.StatusID != 1) 
    {
       audit = CreateAudit(batchID, auditModel);
    }
    else
    {
       if (auditModel.EventTypeID == 16) 
       {
          audit = CreateAudit(batchID, auditModel);
       }
       else
       {
           var checkTrans = GetAllTransactions(batchModel.BatchID);
           if (checkTrans.Count() > 1)
           {
               audit = CreateAudit(batchID, auditModel);
           }
       }
   }
}
else
{
    batch = new Batch()
    {
        CreatedDate = batchModel.CreatedDate
    };

    db.Batches.InsertOnSubmit(batch);
    db.SaveChanges();
    batchID = batch.BatchID;
    audit = CreateAudit(batchID, auditModel);
}

batch.Reason = batchModel.Reason;

db.Audit.InsertOnSubmit(audit);
db.SaveChanges();
scope.Complete();
}
return batch;