LINQ SQL Attach, Update Check set to Never, but still Concurrency conflicts

In the dbml designer, I installed Update Check to Never for all properties. But I still get an exception when executing Attach: "An attempt was made to nest or add an object that is not new, it may have been loaded from another DataContext. This is not supported." This approach seems to have worked for others here, but something must be left out.

        using(TheDataContext dc = new TheDataContext())
        {
            test = dc.Members.FirstOrDefault(m => m.fltId == 1);
        }

        test.Name = "test2";

        using(TheDataContext dc = new TheDataContext())
        {
            dc.Members.Attach(test, true);
            dc.SubmitChanges();
        }
+3
source share
3 answers

, : , DataContext, DataContext. DataContext ( using, ), . ( using). , , . , :

using(TheDataContext dc = new TheDataContext())
{
    var test = dc.Members.FirstOrDefault(m => m.fltId == 1);
    test.Name = "test2";
    dc.SubmitChanges();
}

.

:

( 3 )

( ), . MSDN:

" Attach . , . , , LINQ to SQL . , . , . (LINQ to SQL)."

:

// Get the object the first time by some id
using(TheDataContext dc = new TheDataContext())
{
    test = dc.Members.FirstOrDefault(m => m.fltId == 1);
}

// Somewhere else in the program
test.Name = "test2";

// Again somewhere else
using(TheDataContext dc = new TheDataContext())
{
    // Get the db row with the id of the 'test' object
    Member modifiedMember = new Member()
    {
        Id = test.Id,
        Name = test.Name,
        Field2 = test.Field2,
        Field3 = test.Field3,
        Field4 = test.Field4
    };

    dc.Members.Attach(modifiedMember, true);
    dc.SubmitChanges();
}

, ( db) . , . , db .

+2

datacontext.

, , :

dc.DeferredLoadingEnabled = false

, . - , Update Check Never. : http://complexitykills.blogspot.com/2008/03/disconnected-linq-to-sql-tips-part-1.html

Update Check Never.

0

This is the function in my repository class that I use to update objects

protected void Attach(TEntity entity)
{
   try
    {
       _dataContext.GetTable<TEntity>().Attach(entity);
       _dataContext.Refresh(RefreshMode.KeepCurrentValues, entity);
    }
    catch (DuplicateKeyException ex) //Data context knows about this entity so just update values
    {
       _dataContext.Refresh(RefreshMode.KeepCurrentValues, entity);
    }
}

Where TEntity is your DB class, and depending on you, you may just want to do

_dataContext.Attach(entity);
0
source

Source: https://habr.com/ru/post/1740449/


All Articles