在c#中使用linq更新数据库记录到sql

时间:2011-12-22 21:24:19

标签: c# linq linq-to-sql

我有一个看起来像这样的函数:

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();
  }
}

代码没有崩溃,但它没有更新数据库。我需要改变什么?

3 个答案:

答案 0 :(得分:3)

选择o而不是新的MyObjectMode(),修改:

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

答案 1 :(得分:2)

首先,在查询中执行select new MyObjectModel(),这将始终创建一个新对象,关注从数据库中提取的内容。将其更改为select o

其次,在:

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

有条件地更新对象的值。因此,如果Prop1Prop2为空,则不会更新对象的属性。

答案 2 :(得分:1)

以下代码有效,与您发布的内容几乎相同。

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()