【问题标题】: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实体类型的属性在尝试将实体的状态更改为“已删除”时具有临时值。明确设置永久值
【发布时间】:2021-07-22 12:05:25
【问题描述】:

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

InvalidOperationException:实体类型“EntitasViewModel”上的属性“EntitasID”在尝试将实体状态更改为“已删除”时具有临时值。要么显式设置一个永久值,要么确保数据库配置为为此属性生成值。

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

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

    }

请帮帮我,这是我的论文,谢谢

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

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

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

    相关帖子:

    entity framework Remove vs EntityState.Deleted

    【讨论】:

    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    相关资源
    最近更新 更多