我的基于wpf桌面的应用程序使用ado.net实体框架连接到sql server数据库。在其中一个窗口中,我有一个DataGrid包含来自tbl_users的所有数据,当用户选择其中一行(记录)并单击“编辑”时,应用程序将打开一个新窗口,其中包含用户可以编辑/更新的所有数据。
我的问题是如何通过ADO.NET实体框架将表中某个值的更改(更新/编辑)保存到数据库中?
下面是一些有助于理解情况的代码片段:
1-编辑窗口构造函数

public object objToBeEdited;

public WinWorkers_EditWorker(tbl_users userToBeEdited)
{
    this.Title = Glidus.Properties.Resources.WinWorkers_EditWorker_WinName + Glidus.Properties.Resources.WinApp_WinName;
}

2-方法更新,这不起作用
tbl_users newUser = new tbl_users() //assume inputted values to new ibject
{
    userName = this.WinWorkers_AddEditWorkers_Form_UserName.Text,
    userPassword = this.WinWorkers_AddEditWorkers_Form_Password.Text,
    userAccessLevel = this.WinWorkers_AddEditWorkers_Form_UserAccessLevel.Text
};

//default minimal password length is 4
if (App.IsInputValueMinLenOK(newUser.userPassword, 4))
{
    EntityKey key = App.glidusContext.CreateEntityKey("tbl_users", objToBeEdited);

    if (App.glidusContext.TryGetObjectByKey(key, out objToBeEdited))
    {
        App.glidusContext.ApplyCurrentValues<tbl_users>(key.EntitySetName, newUser);
    }

    try
    {
        App.glidusContext.SaveChanges();
    }
    catch (Exception ex)
    {
        App.UnitedHandleException(ex);
    }

请帮助我,如何实现从数据库更新ado.net记录。
例如,在我的表中有james bond 007,在编辑页面(点击提交页面)之后,我看到了austin powers 008。

最佳答案

要编辑或更新,您可以使用stub entities

Category category = new Category { ID = 5};
Context.AttachTo(“Categories”,category);

Product product = new Product {
     Name = “Bovril”,
     Category = category
};
Context.AddToProducts(product);
Context.SaveChanges();

10-06 06:29
查看更多