在Linq-to-SQL中保存更改 [英] Save changes in Linq-to-SQL

查看:53
本文介绍了在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.

然后我想将其更新到数据库.附加不执行任何操作(运行但不更新). SubmitChanges也不执行任何操作(一起使用时也不执行任何操作).

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

我想念什么?

更新:这是我正在使用的代码:

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

推荐答案

您需要从数据库中获取记录,更新其值,然后调用SubmitChanges()

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

这篇关于在Linq-to-SQL中保存更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆