首页 > 解决方案 > EF 核心/网络。核心 - CRUD - 显式列列表是必须的吗?

问题描述

我确实有以下编辑方法 - 为什么注释行根本不起作用?我真的需要明确提供我在课堂上的所有列吗?

    [HttpPost("edit-item/{id}")]
    public async Task<IActionResult> EditItem(customClass userInput)
    {
        customClass item = await _dbContext.customClass.FindAsync(userInput.ID);

        if (item != null)
        {
            //doesn't work but no error giving - await _dbContext.SaveChangesAsync(); ignoring the changes
            item = userInput; 

            //works - but is it mandatory? Lot of 'stupid' work in case of many columns
            item.TYPE = userInput.TYPE;
            item.CUST = userInput.CUST;
            item.PROD = userInput.PROD;

            try
            {
                await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                "Try again, and if the problem persists, " +
                "see your system administrator.");
            }
        }

        return NoContent();
    }

标签: c#entity-framework-core

解决方案


是的,您必须将任何更新的值分配给从数据库中读取的对象。您不能将传入的对象 ( userInput) 分配给数据库 () 中的实体item。当您这样做时,您只是更改对象引用而不是对象本身。数据库上下文仍然包含对原始数据库实体的引用,并且看不到任何更改。


推荐阅读