简体   繁体   中英

Why is Linq-To-Sql complaining that a record already exists when I"m using context.table.attach()?

I am trying to update all the values of my optimizedSearch record with a completely newly generated POCO without having to manually reset all of the values in my Linq-to-sql object. To do this I set whatever values I want to be not null and then call:

        if (person.xosPodOptimizedSearch == null)
        {
            person.xosPodOptimizedSearch = record;
        }
        else
        {
            context.xosPodOptimizedSearches.Attach(record, true);
            context.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, record);
        }

The purpose of this code is so that if my person record doesn't have an xosPodOptimizedSearch record, then add it. If the person does have one already, I want it updated with whatever values are in the POCO I just created.

However, when this runns and the .attach(record, true) is run Linq-to-sql throws an DuplicateKeyException occurred: Cannot add an entity with a key that is already in use , which is dumb because I know a record exists, which is why I'm using attach() in the first place instead of .InsertOnSubmit() .

How can I get data updated 100% with values that I generated, using none of the values in the DB for that record?

Nevermind, this is my error. I was confusing Linq-to-sql because earlier in my code I had a stray record.xosPerson = person; call, so it only thought the person record was associated with the new record and forgot the old existed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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