You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LINQ更新分类时dbContext.SaveChanges()返回0,预填充表单致失效

问题根源:未判断页面回发导致表单值被重置

兄弟,你这问题我太熟了!核心原因就是你的Page_Load预填充代码没加!IsPostBack判断,导致每次点击编辑按钮回发时,表单里的新值都被原始数据覆盖了,EF自然检测不到变更,SaveChanges()就返回0了。

具体给你捋一遍问题流程:

  • 当你点击btnEditCategory触发页面回发时,ASP.NET的页面生命周期是先执行Page_Load,再执行按钮的点击事件。
  • 你现在的Page_Load不管是不是回发,都会重新从数据库拉取原始分类数据,把你刚在表单里输入的新名称、新描述又改回旧值。
  • 等走到btnEditCategory_Click里,你拿到的tbEditCategoryName.Text其实还是数据库里的原始值,和要更新的实体完全一致,EF的变更追踪机制觉得“这玩意儿没变化啊”,所以SaveChanges()返回0行更新。

解决办法很简单:给Page_Load加非回发判断

修改你的Page_Load方法,只有在页面首次加载(非回发状态)时才执行预填充操作:

protected void Page_Load(object sender, EventArgs e) {
    // Populate Edit Fields
    if (!IsPostBack && Request.QueryString["categoryId"] != null) {
        CategoryDAL categoryDAL = new CategoryDAL();
        RecipeCategory myCategory = new RecipeCategory();
        try {
            addDiv.Attributes["class"] = "hidden";
            editDiv.Attributes["class"] = "display";
            int categoryToGet = Convert.ToInt32(Request.QueryString["categoryId"]);
            myCategory = categoryDAL.GetCategory(categoryToGet);
            tbEditCategoryName.Text = myCategory.Category_Name;
            tbEditCategoryDescription.Text = myCategory.Description;
            ddlEditCategoryGroupList.SelectedValue = Convert.ToString(myCategory.CatGroup_Id);
        } catch(Exception ex) {
            updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
            updateStatus.Visible = true;
            lblStatus.Text = "Could not get Category Info, please try again.";
        }
    }
}

额外给你提两个小优化建议:

  1. DAL层用using包裹DbContext,确保数据库连接资源能及时释放:
public bool EditCategory(int categoryToEdit, RecipeCategory newCategoryInfo) {
    using (RecipeXchangeDBContext dbContext = new RecipeXchangeDBContext()) {
        RecipeCategory myCategory = dbContext.RecipeCategories.FirstOrDefault(c => c.Category_Id == categoryToEdit);
        if (myCategory == null) return false; // 没找到对应分类直接返回失败

        myCategory.Category_Name = newCategoryInfo.Category_Name;
        myCategory.Description = newCategoryInfo.Description;
        myCategory.CatGroup_Id = newCategoryInfo.CatGroup_Id;
        
        try {
            return dbContext.SaveChanges() > 0; // 只要有更新就返回true,不用纠结是否等于1
        } catch (InvalidOperationException ex) {
            // 这里可以加日志记录,方便后续排查问题
            return false;
        }
    }
}
  1. 用FirstOrDefault()替代First(),避免找不到分类时直接抛出异常,代码逻辑更优雅。

内容的提问来源于stack exchange,提问作者KelvinGamer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:29:40