Suppose the primary key of your Item class is ItemId.
Suppose the ItemID for the instance you are attempting to update is 5.
The DataContext has seen an original state for ItemID 5, so it won't let you Attach().
http://msdn.microsoft.com/en-us/library/bb300517.aspx
In this version of Attach, the entity
is assumed to be in its original value
state. After calling this method, you
can then update its fields, for
example with additional data sent from
the client.
There's three normal ways to perform an update in LinqToSql.
If the parameter to this Edit method was originally loaded up from the DataContext, then all you need to do is:
public ActionResult Edit(Item item)
{
Global.DataContext.SubmitChanges();
return View(item);
}
The DataContext tracks changes against objects that it loaded. As a nasty side effect, any modified objects that was loaded by the DataContext are also going to be updated. This is a big reason to not use a single app level DataContext.
If the parameter to this Edit method was new'd up in your code, loaded by a different DataContext, or passed to your code (in other words, the instance has no attached DataContext) then you can do either of these:
public ActionResult Edit(Item item)
{
using(MyDataContext dc = new MyDataContext())
{
//this new DataContext has never heard of my item, so I may Attach.
dc.Items.Attach(item);
//this loads the database record in behind your changes
// to allow optimistic concurrency to work.
//if you turn off the optimistic concurrency in your item class
// then you won't have to do this
dc.Refresh(item, KeepCurrentValues);
dc.SubmitChanges();
}
return View(item);
}
public ActionResult Edit(Item item)
{
original = Global.DataContext.Items.Single(x => x.ItemID = item.ItemID)
//play the changes against the original object.
original.Property1 = item.Property1;
original.Property2 = item.Property2;
Global.DataContext.SubmitChanges();
return View(item);
}
With your question answered, allow me to echo the concern that others have stated for using a static DataContext. This is a poor practice and goes against Microsoft's intended use of the DataContext class.
http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx
In general, a DataContext instance is
designed to last for one "unit of
work" however your application defines
that term. A DataContext is
lightweight and is not expensive to
create. A typical LINQ to SQL
application creates DataContext
instances at method scope or as a
member of short-lived classes that
represent a logical set of related
database operations.