【问题标题】:I can't bind a datagrid using the entity framework我无法使用实体框架绑定数据网格
【发布时间】:2023-03-06 03:41:01
【问题描述】:

我正在尝试使用 WPF 上的实体框架以两种方式绑定数据网格。我无法使用我的数据网格添加任何内容 按下保存后,所有数据都会消失,不会保存在数据库中

<Grid>
    <DataGrid AutoGenerateColumns="True" x:Name="Datag" HorizontalAlignment="Left" Margin="180,24,0,0"  VerticalAlignment="Top" Height="200" Width="551">         
        <DataGrid.Columns>
            <DataGridTextColumn   Width="100" Binding="{Binding id, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            <DataGridTextColumn  Width="100" Binding="{Binding names, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            <DataGridTextColumn  Width="100" Binding="{Binding number, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </DataGrid.Columns>      
    </DataGrid>
</Grid>

这是我的代码:

testsEntities db = new testsEntities();

 public MainWindow()
 {
     InitializeComponent();
     Datag.ItemsSource = db.Test_table.ToList();         
 }

 private void save(object sender, RoutedEventArgs e)
 {
     Datag.Items.Refresh();
     db.SaveChanges();
 }

【问题讨论】:

  • 如果你这样做 .ToList() 我不确定它是否还会更新它。没有它会起作用吗(idk,因为我不熟悉 WPF 和 EF)?
  • 另外,it won't be saved on the data 是什么意思,是否意味着添加后它不在数据库中?
  • 当我使用 Datag.ItemsSource = db.Test_table.ToList();再次或重新运行应用程序我不会找到我添加的数据
  • 我不知道你的评论是什么意思。它当前是否保存到数据库并且不显示它,或者它不显示并且不保存到数据库?
  • 如果我使用表单将数据添加到网格和我的数据库中,那么它将被保存,但是当我使用 datagrid 时它不会保存

标签: c# wpf entity-framework binding datagrid


【解决方案1】:

好的,最后一次编辑。

看来你几乎是在正确的方式,它在数据网格中使用绑定(Binding id, ...),但它似乎没有使用视图模型(你的保存是save(object sender, RoutedEventArgs e)后面的代码中的一个事件)

我会直接从你的数据网格中获取你的数据,如果它不为空,我会处理它并使用实体框架编写它

private void save(object sender, RoutedEventArgs e)
{
    try
    {

        using (var db = new testsEntities())
        {
            if (Datag.ItemsSource == null) 
                return; //Or throw
            var listOfItems = (IEnumerable<Test_table>)Datag.ItemsSource;
            foreach(var item in listOfItems)
            {
                var model = db.Test_table.FirstOrDefault(x=>x.Id == item.Id)
                if (model?.Id > 0)
                {
                    model.names = item.names;
                    model.number = item.number;
                    db.Entry(model).State = EntityState.Modified;
                }
                else
                    db.Test_table.Add(item);

                db.SaveChanges();
            }

        }
    }
    catch (Exception e)
    {
         //Do Something
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    相关资源
    最近更新 更多