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

WPF DataGrid调用Entity Framework SaveChanges()后未实时更新问题

问题根源与解决方案

核心原因

DataGrid无法实时更新Count值,是因为你的Product实体没有实现**INotifyPropertyChanged接口**。EF的DbSet.Local是ObservableCollection<T>,它只会监听集合的增删变更,但不会自动处理实体内部属性的变更通知——只有当实体本身触发属性变更事件时,UI才能实时刷新显示最新值。

另外你的Window_Closing方法里有笔误:_input.Dispose()应该是_context.Dispose(),否则数据库上下文无法正确释放资源。


具体修复步骤

1. 修改Product实体,实现属性变更通知

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class Product : INotifyPropertyChanged
{
    private string _id;
    private int _count;

    public string Id
    {
        get => _id;
        set
        {
            if (_id != value)
            {
                _id = value;
                OnPropertyChanged();
            }
        }
    }

    public int Count
    {
        get => _count;
        set
        {
            if (_count != value)
            {
                _count = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

2. 修正Window_Closing的资源释放代码

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    _context?.Dispose();
}

可选优化与建议

  • 异步操作优化:将数据库操作改为异步,避免阻塞UI线程:
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        var productId = idTextBox.Text.Trim();
        if (string.IsNullOrEmpty(productId))
            return; // 空ID输入验证
    
        Product oldProduct = await _context.Products.FindAsync(productId);
        if(oldProduct != null)
            oldProduct.Count++;
        else
            _context.Products.Add(new Product { Id = productId, Count = 1 });
    
        await _context.SaveChangesAsync();
    }
    
  • 输入验证:添加对idTextBox的非空/格式验证,避免无效数据存入数据库。
  • 绑定优化:可以在DataGrid的绑定中显式指定UpdateSourceTrigger=PropertyChanged(不过本次问题核心是实体通知,此步为可选):
    <DataGridTextColumn Header="COUNT" Binding="{Binding Count, UpdateSourceTrigger=PropertyChanged}"/>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 18:23:13