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

Last Reply 27 days ago By manvendra45

Posted one month ago

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 

You are viewing reply posted by: manvendra45 27 days ago.
Posted 27 days ago

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