newbs
newbs

Reputation: 19

Insert and Save to DB in Catch Statement

How to save data to database in catch statement exception handling ??

I want to write log of the error record to another table to prevent duplication of the primary key

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();
}

The save changes command in catch statement also save all the record in try statement so i get error because of duplicate primary key

All I want is only save the data to LogError table and continue the foreach process

Upvotes: 0

Views: 2090

Answers (1)

Saket Kumar
Saket Kumar

Reputation: 4835

Please verify the Primary Key on your LogErrorImport table. Make sure it is an identity column which is set to auto increment. Do not set this primary key anywhere in your code. If these checks are alright, you shouldn't be getting duplicate Primary Key error.

Update: You will need to define different sets of 'db' context in try and catch block with using statement so that they do not conflict with each other. You might do something like:

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();
   }
}

Upvotes: 1

Related Questions