DataGridView是可编辑的,但不会使用实体框架将更改发送回数据库 [英] DataGridView is editable but does not send changes back to database using Entity Framework

查看:64
本文介绍了DataGridView是可编辑的,但不会使用实体框架将更改发送回数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 DataGridView 绑定到 ComboBox ,以便在<$ c $中选择任何值c> ComboBox ,相应的SID和Mark值将出现在 DataGridView 中。在执行此操作时, DataGridView 是可编辑的,但输入时数据不会保存在数据库中。有办法更新吗?如果还有另一种方法,我必须先警告一下,如果我尝试将整个 Student_Course表绑定到<$ c,则仅需要 DataGridView 中的SID和标记$ c> DataGridView 我得到了我不需要的其他列。

I've bound my DataGridView to my ComboBox so that whatever value is selected in the ComboBox, the corresponding valued for SID and Mark will appear in the DataGridView. The DataGridView is editable when I do this but the data is not saved in the database when it is input. Is there a way to update it? If there's another method, I have to first warn that I only need SID and Mark in the DataGridView, if I try to bind the whole "Student_Course" table to the DataGridView I get other columns I don't need.

private void cboeCID_SelectedIndexChanged_1(object sender, EventArgs e)
{
    var CID = Convert.ToInt32(cboeCID.Text);
    using (var db = new Entities2())
    {
        var course = from c in db.Student_Course
                     where c.CID == CID
                     select new Class1
                     {
                         SID = c.SID,
                         Mark = c.Mark
                     };
        editDataGridView.DataSource = course.ToList();
        Validate();
        editDataGridView.EndEdit();
        editDataGridView.Update();
    }
}

class Class1
{
    public int SID { get; set; }
    public int Mark { get; set; }

}


推荐答案

有上面的代码中有一些重要的问题:

There are some important issues in above code:


  1. 您将查询结果调整为自定义的 Class1 不是您的实体类型。

您使用了 DbContext using 语句中,这意味着 db 将在using语句之后处理,并将

You used a DbContext in using statement which means db is disposed after the using statement and will not track changes.

您在 DbContext的另一个实例上调用了 SaveChanges 不会知道更改,因此什么也不会发生。

You called SaveChanges on another instance of your DbContext which is not aware of changes, so nothing happens.

要解决上述问题,请考虑这些提示:

To solve above issues consider these tips:


  1. db 创建为的字段表单,并在表单 Load 事件中实例化它,并将其用于

  2. 您可以通过以下方式加载数据实体:

  1. Create db as a field of Form and instantiate it in Load event of Form and use it for both loading and saving data.
  2. You can load data entity this way:

db = new Entities2();
db.Student_Course.Where(x => c.CID== CID).ToList();
editDataGridView.DataSource = db.Student_Course.Local; 


  • 您可以通过以下方式保存数据:

  • You can save data this way:

    editDataGridView.EndEdit();
    db.SaveChanges();
    


  • 如果需要使用与实体不同的视图模型进行编辑,则在保存更改时您应该首先使用上下文的另一个实例从数据库加载原始实体,然后为每个实体设置更改字段的值,然后调用 SaveChanges 方法。

    有关更多信息,请查看以下资源:

    For more information take a look at these resources:

    实体框架添加/附加实体状态

    这篇关于DataGridView是可编辑的,但不会使用实体框架将更改发送回数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆