如何编辑 DataGridView 并将更改发送回实体 (LINQ)

How to edit DataGridView and send change back to Entity (LINQ)

我有 WF 项目和这段代码:

public static void fillDataGridUsers(string inDepartment, DataGridView outList)
    {
        var query = context.Users.Where(g => g.SubDepartment.Department.DepartmentName == inDepartment).Select(i =>
        new UsersForEdit
        {
            Id = i.Id,
            Login = i.Login
        });
        BindingSource bindingSource1 = new BindingSource();
        bindingSource1.DataSource = query;
        outList.DataSource = bindingSource1;
    }
    private class UsersForEdit 
    {
        public int Id { get; set; }
        public string Login { get; set; }
    }

我可以编辑 DataGridView,但无法保存它。

private void SaveGrid_Click(object sender, EventArgs e)
    {
        Core.ControlPanel.Manager.saveGridUsers();
    }

public static void saveGridUsers()
    {
        context.SaveChanges();
    }

如果我只加载实体 table - 一切都很好。 当我尝试加载新的 {} 时,我只得到了 ReadOnly DataGridView, 当我尝试用我想要的数据创建 table 时,我无法将其发回或创建一些 link.

例如我需要
新用户编辑 { ID = i.Id, 登录 = i.Login, 部门 = i.Department.DepartmentName });

I can edit DataGridView, but cant save this

上下文仅跟踪使用此上下文具体化(作为查询结果)或 added/attached 实体的更改。当您进行任何投影时,即通过 Select 转换查询结果时,您将获得与上下文无关的实体。

因此,这里没有更改跟踪。当用户修改 UsersForEdit 实例时,不会将任何更改推送回上下文。事实上,SaveChanges 在这种情况下没有任何意义。

When i try load with new {} i got only ReadOnly DataGridView

匿名类型的实例是不可变的。这个:

var foo = new { A = 1, B = "bar" };

最终编译成这样的代码:

class Foo
{
    private readonly int _a;
    private readonly string _b;

    public Foo(int a, string b)
    {
        _a = a;
        _b = b;
    }

    public int A { get { return _a; } }
    public string B { get { return _b; } }
}

因此,您不能更改匿名类型的属性,并且网格视图是只读的。

要实现您想要的效果,您需要将更改推送回上下文。
这可以使用多种方法解决。例如,在断开连接的情况下(当上下文在加载数据后被丢弃时)您可以自己跟踪更改:记住某处更改的实体,并且,当您需要保存更改时,使用新上下文通过 id 加载实体,并从视图模型应用更改( UsersForEdit 个实例)。