簡體   English   中英

如何通過 ADO.NET 實體框架從數據庫更新記錄?

[英]How to update a record from database via ADO.NET Entity Framework?

我的 WPF 基於桌面的應用程序使用 ADO.Net 實體框架來連接到 SQL 服務器數據庫。 在其中一個 windows 中,我有一個DataGrid ,其中包含來自tbl_users的所有數據,當用戶選擇其中一行(記錄)並單擊Edit時,應用程序會打開一個新的 window 表單,其中包括用戶可以編輯/更新的所有數據。

如何通過 ADO.NET 實體框架將表值之一的更改(更新/編輯)保存到數據庫?

以下是一些有助於理解情況的代碼片段:

1 - 編輯 window 構造函數

public object objToBeEdited;

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

2 - 方法更新,不起作用

//assume inputted values to new object
tbl_users newUser = new tbl_users() {
    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

要編輯或更新您可以使用存根實體

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM