Update with LINQ help needed

  • Thread starter Thread starter Nilla
  • Start date Start date
N

Nilla

hi, I'm trying to write the simplest db application using C#, ASP and
LINQtosQL but cannot get the Update function to work. I have used the
codemodel from a sample called IntroToLinq.

My Insert and Get functions work, but the Update does nothing. No
errors are thrown and no changes are made.
Here's my code


In the DBHelper class:
public static void Update<T>(T obj, Action<T> update) where T : class
{
using (var db = GetDatabaseData())
{
db.GetTable<T>().Attach(obj);
update(obj);
db.SubmitChanges();
}
}

public static void UpdateMyclass(Myclass iss)
{
Update<Myclass>(iss, delegate(Myclass i)
{
i.ID = iss.ID;
i.Description = iss.Description;
i.Status = iss.Status;
});
}


In my codebehind for the page where I want to save:

Myclass theObj = MyDB.GetObjById(TextBox1.Text);
theObj.Description = TextBox2.Text;
theObj .ID = TextBox1.Text;

try
{
MyDB.UpdateMyclass (theObj);
............etc.





What is missing in this code? Is there another easy (working..) way
to save this object in the DB using Linq?
THANKS!
 
It looks like you are updating object from itself? So there won't be any
changes detected...

* You get/create "theObj" with some values
* You pass "theObj" to UpdateMyclass as "iss"
* UpdateMyclass creates a delegate, capturing "iss", that when given an
instance "i", updates "i" from "iss"
* UpdateMyclass calls Update<MyClass> passing "iss" as "obj", and the
delegate
* Update<T> gets a context, and attaches "obj"; it then invokes the
delegate and commits

Unwrap that, and the values got copied from the orignal instance to the
same instance...

What did you want to do?

Marc
 
By the way, you can "Attach(obj, true)", which will mark it as dirty. It
won't know *what* is dirty, though - so all values will get updated
(normally only changed values are UPDATEd).

Marc
 
Thank you Marc!

The textbox TextBox2.Text contains a new description for the object,
thats where the difference from original object is.
I tried to use Attach(obj,true) but I got some errors then. (I will
try to recreated it to see what the problem was.)
 
Back
Top