tags:

views:

88

answers:

2

So, here is my hopefully unique spin on this common problem.

I do my query, get my objects then pass the object into a form where it populates the form with the data from the object (this is not passed in by reference).

I then edit the values of the object that was queried (via the form) and then return a new object constructed from the values in the form.

I then want to update this to the database. Attach does nothing (runs but does not update). SubmitChanges also does nothing (and both do nothing when used together).

What am I missing?

Update: here is the code I am using:

// In constructor
_dataMap = new DataMapDataContext();
_addresses = _dataMap.AddressItems
         .Where(address => address.InsertUserName == _currentUser.Name).ToList();



public void EditButtonClick()
{
    using (AddAddressForm form = new AddAddressForm(_addresses[_currentAddress]))
    {
        form.Text = "Edit Address";
        if (DialogResult.OK == form.ShowDialog())
        {
            _addresses[_currentAddress] = form.Item;
            _dataMap.SubmitChanges();
            DisplayItem();
        }
    }
}
+3  A: 

You'll need to get the record from the database, update it's values and then call SubmitChanges()

using(MyDataContext db = new MyDataContext())
{
    // get the record
    Product dbProduct = db.Products.Single(p => p.ID == 1);

    // set new values
    dbProduct.Quantity = 5; 
    dbProduct.IsAvailable = false;

    // save them back to the database
    db.SubmitChanges();
}
Naeem Sarfraz
where's your using/dispose? tsk, tsk. =)
RPM1984
@RPM1984, thanks
Naeem Sarfraz
A: 

Turns out I was doing almost everything right.

I just needed to pass in the object I was editing by reference. That way when it got changed, it was not a new object that was returned, but the same one (that Linq-to-SQL already knew about.)

These are the two lines from the code above that got changed:

AddressItem itemToEdit = _addresses[_currentAddress];
using (AddAddressForm form = new AddAddressForm(ref itemToEdit))
Vaccano
@This is so terribly wrong on how you would do this
msarchet
@msarchet - This is just for a demo, so it is not that important now, but for future reference, why is this wrong? I am not a huge user of Linq-to-SQL and when I do use it I usually have it calling stored procedures for my inserting and updating. So I am not familiar with this aspect of Linq-To-SQL. If you have a better way *that has a different class than the one that has the data context and the query doing the updating* then post it as an answer and I will select it. If not, well then....
Vaccano