LinqToSQL无法更新两次

时间:2012-09-14 02:44:53

标签: linq linq-to-sql datacontext insert-update

我尝试使用相同的数据更新两次,但它会抛出异常

    public void UpdateOnSubmit<T>(T data) where T : class
    {
        lock (_lockObj)
        {
            using (DataModel dx = new DataModel(this._adapter.ConnectionString))
            {
                dx.GetTable<T>().Attach(data);
                dx.Refresh(RefreshMode.KeepCurrentValues, data);
                dx.SubmitChanges();
            }
        }
    }

例外是

An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.

首次更新是成功,但不是第二次更新。提前致谢

此致

布赖恩

1 个答案:

答案 0 :(得分:0)

好像我再次找到了解决方案。我只是将DeferredLoadingEnabled设置为false,它就像一个魅力。

    public void UpdateOnSubmit<T>(T data) where T : class
    {
        lock (_lockObj)
        {
            using (DataModel dx = new DataModel(this._adapter.ConnectionString))
            {
                dx.DeferredLoadingEnabled = false;
                dx.GetTable<T>().Attach(data);
                dx.Refresh(RefreshMode.KeepCurrentValues, data);
                dx.SubmitChanges();
            }
        }
    }