簡體   English   中英

使用linq將數據庫記錄更新為C#中的sql

[英]updating a database record with linq to sql in c#

我有一個看起來像這樣的函數:

public UpdateRecord(MyObjectModel TheObject, int TheUserID)
{
  using (MyDataContextModel TheDC = new MyDataContextModel())
  {
     var TheObjectInDB = (from o in TheDC.TheObjects
                          where o.ObjectID == TheObject.ObjectID
                          select new MyObjectModel()).SingleOrDefault();

     if (TheObject.Prop1 != null) { TheObjectInDB.Prop1 = TheObject.Prop1; }
     if (TheObject.Prop2 != null) { TheObjectInDB.Prop2 = TheObject.Prop2; }

     TheDC.SubmitChanges();
  }
}

代碼沒有崩潰,但是沒有更新數據庫。 我需要更改什么?

選擇o代替new MyObjectMode(),修改:

var TheObjectInDB = (from o in TheDC.TheObjects
                          where o.ObjectID == TheObject.ObjectID
                          select o).SingleOrDefault();

首先,您確實在查詢中select new MyObjectModel() ,它將始終根據您從數據庫中提取的內容創建一個新的對象。 更改為select o

其次,在:

if (TheObject.Prop1 != null) { TheObjectInDB.Prop1 = TheObject.Prop1; }
if (TheObject.Prop2 != null) { TheObjectInDB.Prop2 = TheObject.Prop2; }

您可以有條件地更新對象的值。 因此,如果Prop1Prop2為null,則不會更新對象的屬性。

以下代碼有效,並且幾乎與您發布的代碼相同。

DataContext dc = new DataContext(ConnectionString);
var q = from a in dc.GetTable<Employee>()
        where a.EmployeeID == this.EmployeeID
        select a;
Employee temp = q.Single<Employee>();
temp.EmployeeActiveStatus = this.EmployeeActiveStatus;
temp.EmployeeName = this.EmployeeName;
temp.EmployeeUserID = this.EmployeeUserID;
temp.EmployeeCreateModifyDate = this.EmployeeCreateModifyDate;
temp.EmployeePaperWork = this.EmployeePaperWork;
dc.SubmitChanges();

我看到的唯一主要區別是該行:選擇新的MyObjectMode())。SingleOrDefault()

暫無
暫無

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

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