简体   繁体   English

如何在 Linq-to-SQL 中保存更改?

[英]How to save changes in Linq-to-SQL?

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). SubmitChanges 也不做任何事情(并且两者一起使用时什么也不做)。

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

You'll need to get the record from the database, update it's values and then call SubmitChanges()您需要从数据库中获取记录,更新它的值,然后调用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();
}

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.)这样,当它被更改时,返回的不是一个新对象,而是同一个对象(Linq-to-SQL 已经知道了)。

These are the two lines from the code above that got changed:这些是上面代码中发生更改的两行:

AddressItem itemToEdit = _addresses[_currentAddress];
using (AddAddressForm form = new AddAddressForm(ref itemToEdit))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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