简体   繁体   中英

updating a database record with linq to sql in c#

I have a function that looks like this:

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

The code is not crashing but it's not updating the DB. What do I need to change?

select o instead of new MyObjectMode(), Modify:

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

First of all you do select new MyObjectModel() in your query which will always create a new object regardsess of what you pull from the database. Change that to select o .

Secondly, in:

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

you update the object's values conditionally. So if Prop1 and Prop2 are null the object's properties won't be updated.

The following code works and it is almost the same as what you posted.

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

The only major difference that I see is the line: select new MyObjectMode()).SingleOrDefault()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM