在Catch语句中插入并保存到DB

时间:2017-05-16 07:55:47

标签: c# entity-framework

如何在catch语句异常处理中将数据保存到数据库?

我想将错误记录的日志写入另一个表以防止重复主键

foreach(var i in impCSV)
{
    try
    {
        var addrDet = new AddrDetail()
        {
            Road = i.w_addr1,
            Road2 = i.w_addr2,
            Road3 = i.w_addr3,
            City = i.w_city,
            Zipcode = i.w_zip
        };

        var invoice = new Invoice()
        {
            InvoiceNo = i.rec_no
        };

        var image = new Models.Image()
        {
            Image1 = null
        };

        var detail = new DetailPengiriman()
        {
            TrDate = null,
            InsertDate = DateTime.Parse(i.doc_dt)
        };

        var cust = db.Customers.Find(i.cust_id);                  
        if (cust !=null)
        {
            cust.CustID = i.cust_id;
            cust.Phone = i.w_phone1;
            cust.CustComp = i.company;
            cust.Fullname = i.fullname;

            db.Entry(cust).State = EntityState.Modified;
        }
        else
        {
            cust = new Customer()
            {
                CustID = i.cust_id,
                Phone = i.w_phone1,
                CustComp = i.company,
                Fullname = i.fullname
            };

            db.Customers.Add(cust);
        }
        invoice.CustID = cust.CustID;

        db.AddrDetails.Add(addrDet);
        invoice.AddrDetID = addrDet.AddrDetID;      

        db.Images.Add(image);
        invoice.ImageID = image.ImageID;

        db.Invoices.Add(invoice);
        stat.InvoiceNo = invoice.InvoiceNo;
        detail.InvoiceNo = invoice.InvoiceNo;

        detail.CompID = compID;
        db.DetailPengirimen.Add(detail);

        db.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        foreach (var entityValidationErrors in ex.EntityValidationErrors)
        {
            foreach (var validationError in entityValidationErrors.ValidationErrors)
            {
                Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
            }
        }
    }
    catch (Exception e)
    {
        var logEr = new LogErrorImport()
        {
            custid = i.cust_id,
            fullname = i.fullname,
            company = i.company,
            re = i.rec_no,
            doc = i.doc_dt,
            addr1 = i.w_addr1,
            addr2 = i.w_addr2,
            addr3 = i.w_addr3,
            city = i.w_city,
            zip = i.w_zip,
            phone = i.w_phone1
        };
        db.LogErrorImports.Add(logEr);
        db.SaveChanges();
}

catch语句中的save changes命令也保存了try语句中的所有记录,因此由于重复的主键而出现错误

我想要的只是将数据保存到LogError表并继续foreach过程

1 个答案:

答案 0 :(得分:1)

请验证LogErrorImport表上的主键。确保它是一个设置为自动增量的标识列。不要在代码中的任何位置设置此主键。如果这些检查没有问题,则不应该出现重复的主键错误。

<强>更新 您需要定义不同的&#39; db&#39; trycatch中的上下文阻止using语句,以便它们不会相互冲突。您可以执行以下操作:

try
{
   using (var _context = new DBContext())
   {
      //Normal save logic here
     _context.Save();
   }
}
catch(Exception ex)
{
   using (var _context = new DBContext())
   {
      //Log error here
     _context.Save();
   }
}
相关问题