Check if record Exists then update else insert in Database using Entity Framework in ASP.Net Core

manvendra45
 
on Oct 18, 2019 06:57 AM
7846 Views

Hello All,

I am working on asp core with entity framework. i want to insert record if not a single record exists else update record 

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(InstitutionDetails schooldetails)
        {
            if (ModelState.IsValid)
            {
                var details = db.InstitutionDetails.FirstOrDefault();
                
                    var files = HttpContext.Request.Form.Files;
               
                if (details == null)
                {
                    db.Add(schooldetails);
                    await db.SaveChangesAsync();
                }
                else
                {
                    db.Update(schooldetails);
                    await db.SaveChangesAsync();
                }
               
                return RedirectToAction("institution");
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors);
            }
            return View(schooldetails);
        }

In Given code snipet it save new record everytime.

Please help me anyone 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 18, 2019 07:27 AM
manvendra45 says:
if (details == null)

 Here you need to chack with any primary key column value with your database record for existance of the record.

For reference you can check below article.

Check Username Availability (Exists) in Database using jQuery AJAX in ASP.Net MVC

manvendra45
 
on Oct 21, 2019 12:06 PM

Here we have to use EntityState function and have to check id of same model which i am binding.

If Id is null then add new record else update the same record of same instance.

if (schooldetails.Id == 0)
{
    db.InstitutionDetails.Add(schooldetails);
}
else
{
    db.Entry(schooldetails).State = EntityState.Modified;
}