如果数据库中已经存在,如何更新值,如果没有则插入新记录?

时间:2017-09-14 08:06:57

标签: asp.net-mvc excel linq

我已经创建了一个验证来检查excel文件中的值,如果它已经存在于数据库中的行值。我想创建操作,如果值已经存在,那么我的记录更新,如果不存在于数据库,则插入为新记录。

这里是完整的代码。

[ValidateAntiForgeryToken]
public ActionResult ImportDataAgens(HttpPostedFileBase excelfileRekn)
{
    if (excelfileRekn == null || excelfileRekn.ContentLength == 0)
    {
        ViewBag.Error = "Please Select File...";
        return View("ImportDataAgens");
    }
    else
    {
        if (excelfileRekn.FileName.EndsWith("xls") || excelfileRekn.FileName.EndsWith("xlsx"))
        {
            string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            string filename = Path.GetFileName(excelfileRekn.FileName);
            string DocFileNames = newFileName + "-" + filename;
            string path = System.IO.Path.Combine(Server.MapPath("~/UploadFile/DataAgen/"), DocFileNames);

            if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
                excelfileRekn.SaveAs(path);
                //read data from file excel 

                Excel.Application application = new Excel.Application();
                Excel.Workbook workbook = application.Workbooks.Open(path);
                Excel.Worksheet worksheet = workbook.ActiveSheet;
                Excel.Range range = worksheet.UsedRange;
                List<DMInformasiDataAgen> listTempRekn = new List<DMInformasiDataAgen>();

                for (int row = 3; row <= range.Rows.Count; row++)
                {

                    DMInformasiDataAgen rk = new DMInformasiDataAgen();

                    /* var NewUserIDAgent = ((Excel.Range)range.Cells[row, 1]).Text;

                    var NewNamaAgen = ((Excel.Range)range.Cells[row, 2]).Text;
                    //rk.NamaAgen = NewNamaAgen;*/
                    rk.SandiBank = ((Excel.Range)range.Cells[row, 1]).Text;
                    rk.UserIDAgen = ((Excel.Range)range.Cells[row, 2]).Text;
                    rk.NamaAgen = ((Excel.Range)range.Cells[row, 3]).Text;
                    var NewNomorIdentifikasiAgen = ((Excel.Range)range.Cells[row, 4]).Text;
                    rk.NomorIdentifikasiAgen = NewNomorIdentifikasiAgen;


                    if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
                    {
                        int RowNo = row;
                        var hitung = listTempRekn.Count + 4;
                        ModelState.AddModelError("", "Nomor Identifikasi Sudah ada sebelumnya ! Pada baris ke " + hitung + " Pada EXCEL File !");
                        return View("ImportDataAgens");
                    }

                    rk.NomordanTanggalPerjanjian = ((Excel.Range)range.Cells[row, 5]).Text;


                    rk.TglPelaksanaan = ((Excel.Range)range.Cells[row, 6]).Value;

                    rk.JenisAgen = ((Excel.Range)range.Cells[row, 7]).Text;
                    rk.KlasifikasiAgen = ((Excel.Range)range.Cells[row, 8]).Text;
                    rk.JenisUsahaAgen = ((Excel.Range)range.Cells[row, 9]).Text;
                    rk.KodePos = ((Excel.Range)range.Cells[row, 10]).Text;
                    rk.LatitudeLongitudinal = ((Excel.Range)range.Cells[row, 11]).Text;
                    rk.KabupatenKota = ((Excel.Range)range.Cells[row, 12]).Text;
                    rk.ElectronicDevice = ((Excel.Range)range.Cells[row, 13]).Text;
                    rk.JaringanKantorBank = ((Excel.Range)range.Cells[row, 14]).Text;
                    rk.KategoriJaringanKantorBank = ((Excel.Range)range.Cells[row, 15]).Text;
                    rk.StatusPerkembanganAgen = ((Excel.Range)range.Cells[row, 16]).Text;
                    rk.Keterangan = ((Excel.Range)range.Cells[row, 17]).Text;

                    if (((Excel.Range)range.Cells[row, 18]).Value == null)
                    {

                        int RowNo = row;
                        var hitung = listTempRekn.Count + 4;
                        ModelState.AddModelError("", "Tolong periksa PERIODE Pada baris ke " + hitung + " Pada EXCEL File !");
                        return View("ImportDataAgens");
                    }

                    rk.Periode = ((Excel.Range)range.Cells[row, 18]).Value;
                    string valueA = System.Web.HttpContext.Current.User.Identity.Name;
                    rk.CreateBy = valueA;
                    rk.CreateDate = DateTime.Today;

                    if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
                    {
                        int RowNo = row;
                        var hitung = listTempRekn.Count + 4;
                        ModelState.AddModelError("", "The Number Of Agent Already Exist on  " + hitung + " the Template EXCEL File !");
                        return View("ImportDataAgens");
                    }

                    if (ModelState.IsValid)
                    {
                        listTempRekn.Add(rk);
                        db.DMInformasiDataAgens.Add(rk);
                        db.SaveChanges();
                        var hitung = listTempRekn.Count;
                        //range.Rows.Count - 2;
                        TempData["AlertMessage"] = "Import Data Selesai " + hitung + " Records Sudah Tersimpan...";
                    }
                }

                return RedirectToAction("Index", "DataAgens");
        }
        else
        {
            ViewBag.Error = "File Type is incorrect <br>";
            return View("ImportDataAgens");
        }

    }

}

这里的代码我检查已经存在的值:

**if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
{
    int RowNo = row;
    var hitung = listTempRekn.Count + 4;
    ModelState.AddModelError("", " The Number Of Agent Already Exist on  " + hitung + " the Template EXCEL File !");
    return View("ImportDataAgens");
}**

如果值已经存在(代理号),那么如何创建操作然后我的记录更新,如果没有则插入新记录?

1 个答案:

答案 0 :(得分:2)

var chkItem = x.firstOrDefault(your condition);
if(chkItem != null)
{
    //update your record.
}
else{
    //insert into database
}