1

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?

2
  • Maybe TheObjectInDB returns null? Commented Dec 22, 2011 at 21:28
  • This looks like a SELECT statement to me, so why should it be UPDATEing the DB? Commented Dec 22, 2011 at 21:31

3 Answers 3

3

select o instead of new MyObjectMode(), Modify:

var TheObjectInDB = (from o in TheDC.TheObjects
                          where o.ObjectID == TheObject.ObjectID
                          select o).SingleOrDefault();
Sign up to request clarification or add additional context in comments.

1 Comment

Oh duh!! Thanks for the answer, I got!
2

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.

3 Comments

"So if Prop1 and Prop2 are null the object's properties won't be updated." Yes, that's what I'm looking to do: if Prop1 AND Prop2 are empty then no update and if Prop1 has a new value but Prop2 is empty then only update Prop1. Is that going to cause problems?
@frenchie No, it shouldn't cause problems, but the first part obviously does.
ok, cool. I did make the change and it was select o!! Thanks for the tip.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.