0

When i try to delete some data, i got an error message like this

InvalidOperationException: The property 'EntitasID' on entity type 'EntitasViewModel' has a temporary value while attempting to change the entity's state to 'Deleted'. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

this is my delete function in controller:

   ''' [Authorize]
    public IActionResult Delete(int? id)
    {
        EntitasViewModel entitasViewModel = _context.Master_Entitas.Where(p => p.EntitasID == id)
            .Include(p => p.HoldingViewModel).FirstOrDefault();
        return View(entitasViewModel);
    }

    // POST: Entitas/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    [Authorize]
    public IActionResult DeleteConfirmed(int? id)
    {
            EntitasViewModel entitasViewModel = new EntitasViewModel();
            _context.Attach(entitasViewModel);
            _context.Entry(entitasViewModel).State = EntityState.Deleted;

            _context.SaveChanges();
            _notyf.Success("Data berhasil dihapus", 3);
            
            return RedirectToAction(nameof(View));
       
    }'''

this is my model:

public class EntitasViewModel
    {
        [Key]
        public int EntitasID { get; set; }
        public string NamaEntitas { get; set; }

        [ForeignKey("HoldingViewModel")]
        [DisplayName("HoldingViewModel")]
        public int HoldingID { get; set; }
        public virtual HoldingViewModel HoldingViewModel { get; set; }

        [NotMapped]
        public List<HoldingViewModel> master_Holding { get; set; }

    }

Please help me guys this is for my thesis thank youu

1 Answers1

1

When you want to delete data, you should get the model by it, not create a new one.

public IActionResult DeleteConfirmed(int? id)
{
        EntitasViewModel entitasViewModel = _context.Master_Entitas.Where(p => p.EntitasID == id)
        .Include(p => p.HoldingViewModel).FirstOrDefault();
        _context.Entry(entitasViewModel).State = EntityState.Deleted;

        _context.SaveChanges();
        _notyf.Success("Data berhasil dihapus", 3);
        return RedirectToAction(nameof(View));
}

Related Post:

entity framework Remove vs EntityState.Deleted

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
  • @NadyarahmaLestanti If my reply is helpful, please accept it as answer(click on the mark option beside the reply to toggle it from greyed out to fill in.), see https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Jason Pan Jul 22 '21 at 04:24