尝试将实体的状态更改为 'Deleted' 时,实体类型的 属性 具有临时值。显式设置永久值

The property on entity type has a temporary value while attempting to change the entity's state to 'Deleted'. Either set a permanent value explicitly

当我尝试删除一些数据时,我收到了这样的错误消息

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.

这是我在控制器中的删除功能:

   ''' [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));
       
    }'''

这是我的模型:

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

    }

请大家帮帮我这是我的论文谢谢你

当你要删除数据时,你应该通过它获取模型,而不是创建一个新的。

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

相关Post: