<p>When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException.</p>

<pre><code>var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath);
var deviceSessionRecord = ctx.Sessions.First(sess =&gt; sess.SessionRecId == args.DeviceSessionId);

deviceSessionRecord.IsActive = false;
deviceSessionRecord.Disconnected = DateTime.Now;

ctx.SubmitChanges();
</code></pre>

<p>The query generates the following SQL:</p>

<pre><code>UPDATE [Sessions]
SET [Is_Active] = @p0, [Disconnected] = @p1
WHERE 0 = 1
-- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>

<p>The obvious problem is the <strong>WHERE 0=1</strong>, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key.  Also when catching the "ChangeConflictException" there is no additional information about why this failed.  I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update)</p>

<p>What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database.</p>

<pre><code>UPDATE [Sessions]
SET [Is_Active] = @p4, [Disconnected] = @p5
WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3)
-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b]
-- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d]
-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM]
-- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV]
-- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>

<p>I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes.</p>

<p>I guess this is almost a two part question:</p>

<ol>
<li>Why is the exception being thrown?</li>
<li>After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient.  Is this the way this always works?  Is there a setting to just check the primary key?</li>
</ol>

<p>I've been fighting with this for the past two hours so any help would be appreciated.</p>

[{'answer_id': 83999, 'author': 'Sam', 'author_id': 7021, 'author_profile': 'https://Stackoverflow.com/users/7021', 'pm_score': 9, 'selected': True, 'text': '<p>Thats nasty, but simple:</p>\n\n<p>Check if the data types for all fields in the O/R-Designer match the data types in your SQL table.\n<strong>Double check for nullable!</strong> A column should be either nullable in both the O/R-Designer and SQL, or not nullable in both.</p>\n\n<p>For example, a NVARCHAR column "title" is marked as NULLable in your database, and contains the value NULL. Even though the column is marked as NOT NULLable in your O/R-Mapping, LINQ will load it successfully and set the column-String to null.</p>\n\n<ul>\n<li>Now you change something and call\nSubmitChanges().</li>\n<li>LINQ will generate a SQL query\ncontaining "WHERE [title] IS NULL", to make sure the title has not been changed by someone else.</li>\n<li>LINQ looks up the properties of\n[title] in the mapping.</li>\n<li>LINQ will find [title] NOT NULLable.</li>\n<li>Since [title] is NOT NULLable, by\nlogic it never could be NULL!</li>\n<li>So, optimizing the query, LINQ\nreplaces it with "where 0 = 1", the\nSQL equivalent of "never".</li>\n</ul>\n\n<p>The same symptom will appear when the data types of a field does not match the data type in SQL, or if fields are missing, since LINQ will not be able to make sure the SQL data has not changed since reading the data.</p>\n'}, {'answer_id': 512975, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I solved this error by redragging over a table from the server explorer to the designer and re-building.</p>\n'}, {'answer_id': 663136, 'author': 'Michael Nero', 'author_id': 1456754, 'author_profile': 'https://Stackoverflow.com/users/1456754', 'pm_score': 2, 'selected': False, 'text': '<p>I don\'t know if you\'ve found any satisfactory answers to your question, but I posted a similar question and eventually answered it myself. It turned out that the NOCOUNT default connection option was turned on for the database, which caused a ChangeConflictException for every update made with Linq to Sql. You can refer to my post at <a href="https://stackoverflow.com/questions/663822/changeconflictexception-in-linq-to-sql-update">here</a>.</p>\n'}, {'answer_id': 3632983, 'author': 'Matt Sherman', 'author_id': 70613, 'author_profile': 'https://Stackoverflow.com/users/70613', 'pm_score': 4, 'selected': False, 'text': '<p>There is a method on DataContext called <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.refreshmode.aspx" rel="noreferrer">Refresh</a> which may help here. It allows you to reload the database record before changes are submitted, and offers different modes to determine which values to keep. "KeepChanges" seems the smartest for my purposes, it is intended to merge my changes with any non-conflicting change that happened in the database in the meantime.</p>\n\n<p>If I understand it correctly. :)</p>\n'}, {'answer_id': 6101981, 'author': 'Chris Moschini', 'author_id': 176877, 'author_profile': 'https://Stackoverflow.com/users/176877', 'pm_score': 4, 'selected': False, 'text': '<p>This can also be caused by using more than one DbContext.</p>\n\n<p>So for example:</p>\n\n<pre><code>protected async Task loginUser(string username)\n{\n    using(var db = new Db())\n    {\n        var user = await db.Users\n            .SingleAsync(u =&gt; u.Username == username);\n        user.LastLogin = DateTime.UtcNow;\n        await db.SaveChangesAsync();\n    }\n}\n\nprotected async Task doSomething(object obj)\n{\n    string username = "joe";\n    using(var db = new Db())\n    {\n        var user = await db.Users\n            .SingleAsync(u =&gt; u.Username == username);\n\n        if (DateTime.UtcNow - user.LastLogin &gt;\n            new TimeSpan(0, 30, 0)\n        )\n            loginUser(username);\n\n        user.Something = obj;\n        await db.SaveChangesAsync();\n    }\n}\n</code></pre>\n\n<p>This code will fail from time to time, in ways that seem unpredictable, because the user is used in both contexts, changed and saved in one, then saved in the other. The in-memory representation of the user who owns "Something" doesn\'t match what\'s in the database, and so you get this lurking bug.</p>\n\n<p>One way to prevent this is to write any code that might ever be called as a library method in such a way that it takes an optional DbContext:</p>\n\n<pre><code>protected async Task loginUser(string username, Db _db = null)\n{\n    await EFHelper.Using(_db, async db =&gt;\n    {\n        var user = await db.Users...\n        ... // Rest of loginUser code goes here\n    });\n}\n\npublic class EFHelper\n{\n    public static async Task Using&lt;T&gt;(T db, Func&lt;T, Task&gt; action)\n        where T : DbContext, new()\n    {\n        if (db == null)\n        {\n            using (db = new T())\n            {\n                await action(db);\n            }\n        }\n        else\n        {\n            await action(db);\n        }\n    }\n}\n</code></pre>\n\n<p>So now your method takes an optional database, and if there isn\'t one, goes and makes one itself. If there is it just reuses what was passed in. The helper method makes it easy to reuse this pattern across your app.</p>\n'}, {'answer_id': 7322320, 'author': 'rtpHarry', 'author_id': 156388, 'author_profile': 'https://Stackoverflow.com/users/156388', 'pm_score': 0, 'selected': False, 'text': "<p>I know this question has long since been answered but here I have spent the last few hours banging my head against a wall and I just wanted to share my solution which turned out not to be related to any of the items in this thread:</p>\n\n<h2>Caching!</h2>\n\n<p>The select() part of my data object was using caching. When it came to updating the object a Row Not Found Or Changed error was cropping up. </p>\n\n<p>Several of the answers did mention using different DataContext's and in retrospect this is probably what was happening but it didn't instantly lead me to think caching so hopefully this will help somebody!</p>\n"}, {'answer_id': 8272354, 'author': 'jamisonLikeCode', 'author_id': 66265, 'author_profile': 'https://Stackoverflow.com/users/66265', 'pm_score': 0, 'selected': False, 'text': "<p>I recently encountered this error, and found the problem was not with my Data Context, but with an update statement firing inside a trigger after Commit was being called on the Context. \nThe trigger was trying to update a non-nullable field with a null value, and it was causing the context to error out with the message mentioned above.</p>\n\n<p>I'm adding this answer solely to help others dealing with this error and not finding a resolution in the answers above.</p>\n"}, {'answer_id': 11308978, 'author': 'Johan Paul', 'author_id': 1211542, 'author_profile': 'https://Stackoverflow.com/users/1211542', 'pm_score': 2, 'selected': False, 'text': '<p>I fixed this by adding <code>(UpdateCheck = UpdateCheck.Never)</code> to all <code>[Column]</code> definitions. </p>\n\n<p>Does not feel like an appropriate solution, though. In my case it seems to be related to the fact that this table has an association to another table from where a row is deleted.</p>\n\n<p>This is on Windows Phone 7.5.</p>\n'}, {'answer_id': 31046866, 'author': 'srinivas vadlamudi', 'author_id': 4305725, 'author_profile': 'https://Stackoverflow.com/users/4305725', 'pm_score': 0, 'selected': False, 'text': '<p>I have also got this error because of using two different contexts. I resolved this issue by using single data context. </p>\n'}, {'answer_id': 32279975, 'author': 'Tomas Kubes', 'author_id': 518530, 'author_profile': 'https://Stackoverflow.com/users/518530', 'pm_score': 5, 'selected': False, 'text': '<p>First, it useful to know, what is causing the problem. Googling solution should help, you can log the details (table, column, old value, new value) about the conflict to find better solution for solving the conflict later:</p>\n\n<pre><code>public class ChangeConflictExceptionWithDetails : ChangeConflictException\n{\n    public ChangeConflictExceptionWithDetails(ChangeConflictException inner, DataContext context)\n        : base(inner.Message + " " + GetChangeConflictExceptionDetailString(context))\n    {\n    }\n\n    /// &lt;summary&gt;\n    /// Code from following link\n    /// https://ittecture.wordpress.com/2008/10/17/tip-of-the-day-3/\n    /// &lt;/summary&gt;\n    /// &lt;param name="context"&gt;&lt;/param&gt;\n    /// &lt;returns&gt;&lt;/returns&gt;\n    static string GetChangeConflictExceptionDetailString(DataContext context)\n    {\n        StringBuilder sb = new StringBuilder();\n\n        foreach (ObjectChangeConflict changeConflict in context.ChangeConflicts)\n        {\n            System.Data.Linq.Mapping.MetaTable metatable = context.Mapping.GetTable(changeConflict.Object.GetType());\n\n            sb.AppendFormat("Table name: {0}", metatable.TableName);\n            sb.AppendLine();\n\n            foreach (MemberChangeConflict col in changeConflict.MemberConflicts)\n            {\n                sb.AppendFormat("Column name : {0}", col.Member.Name);\n                sb.AppendLine();\n                sb.AppendFormat("Original value : {0}", col.OriginalValue.ToString());\n                sb.AppendLine();\n                sb.AppendFormat("Current value : {0}", col.CurrentValue.ToString());\n                sb.AppendLine();\n                sb.AppendFormat("Database value : {0}", col.DatabaseValue.ToString());\n                sb.AppendLine();\n                sb.AppendLine();\n            }\n        }\n\n        return sb.ToString();\n    }\n}\n</code></pre>\n\n<p>Create helper for wrapping your sumbitChanges:</p>\n\n<pre><code>public static class DataContextExtensions\n{\n    public static void SubmitChangesWithDetailException(this DataContext dataContext)\n    {   \n        try\n        {         \n            dataContext.SubmitChanges();\n        }\n        catch (ChangeConflictException ex)\n        {\n            throw new ChangeConflictExceptionWithDetails(ex, dataContext);\n        }           \n    }\n}\n</code></pre>\n\n<p>And then call submit changes code:</p>\n\n<pre><code>Datamodel.SubmitChangesWithDetailException();\n</code></pre>\n\n<p>Finally, log the exception in your global exception handler:</p>\n\n<pre><code>protected void Application_Error(object sender, EventArgs e)\n{         \n    Exception ex = Server.GetLastError();\n    //TODO\n}\n</code></pre>\n'}, {'answer_id': 33344994, 'author': 'Wojtek', 'author_id': 3454348, 'author_profile': 'https://Stackoverflow.com/users/3454348', 'pm_score': 0, 'selected': False, 'text': '<p>In my case the problem was with the server-wide user options.\nFollowing:</p>\n\n<p><a href="https://msdn.microsoft.com/en-us/library/ms190763.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/ms190763.aspx</a></p>\n\n<p>I enabled the NOCOUNT option in hope to get some performance benefits:</p>\n\n<pre><code>EXEC sys.sp_configure \'user options\', 512;\nRECONFIGURE;\n</code></pre>\n\n<p>and this turns out to break Linq\'s checks for the Affected Rows (as much as I can figure it out from .NET sources), leading to <strong>ChangeConflictException</strong></p>\n\n<p>Resetting the options to exclude the 512 bit fixed the problem.</p>\n'}, {'answer_id': 39021687, 'author': 'MarceloBarbosa', 'author_id': 3545349, 'author_profile': 'https://Stackoverflow.com/users/3545349', 'pm_score': 2, 'selected': False, 'text': '<p>This is what you need to override this error on C# code:</p>\n\n<pre><code>            try\n            {\n                _db.SubmitChanges(ConflictMode.ContinueOnConflict);\n            }\n            catch (ChangeConflictException e)\n            {\n                foreach (ObjectChangeConflict occ in _db.ChangeConflicts)\n                {\n                    occ.Resolve(RefreshMode.KeepChanges);\n                }\n            }\n</code></pre>\n'}, {'answer_id': 39837945, 'author': 'John Pasquet', 'author_id': 926053, 'author_profile': 'https://Stackoverflow.com/users/926053', 'pm_score': 0, 'selected': False, 'text': "<p>After employing qub1n's answer, I found that the issue for me was that I had inadvertently declared a database column to be decimal(18,0).  I was assigning a decimal value, but the database was changing it, stripping the decimal portion.  This resulted in the row changed issue.</p>\n\n<p>Just adding this if anyone else runs into a similar issue.</p>\n"}, {'answer_id': 62459863, 'author': 'CAK2', 'author_id': 773906, 'author_profile': 'https://Stackoverflow.com/users/773906', 'pm_score': 1, 'selected': False, 'text': '<p>In my case, the error was raised when two users having different LINQ-to-SQL data contexts updated the same entity in the same way.  When the second user attempted the update, the copy they had in their data context was stale even though it was read after the first update had completed.  </p>\n\n<p>I discovered the explanation and solution in this article by Akshay Phadke:  <a href="https://www.c-sharpcorner.com/article/overview-of-concurrency-in-linq-to-sql/" rel="nofollow noreferrer">https://www.c-sharpcorner.com/article/overview-of-concurrency-in-linq-to-sql/</a></p>\n\n<p>Here\'s the code I mostly lifted:</p>\n\n<pre><code>try\n{\n    this.DC.SubmitChanges();\n}\ncatch (ChangeConflictException)\n{\n     this.DC.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);\n\n     foreach (ObjectChangeConflict objectChangeConflict in this.DC.ChangeConflicts)\n     {\n         foreach (MemberChangeConflict memberChangeConflict in objectChangeConflict.MemberConflicts)\n         {\n             Debug.WriteLine("Property Name = " + memberChangeConflict.Member.Name);\n             Debug.WriteLine("Current Value = " + memberChangeConflict.CurrentValue.ToString());\n             Debug.WriteLine("Original Value = " + memberChangeConflict.OriginalValue.ToString());\n             Debug.WriteLine("Database Value = " + memberChangeConflict.DatabaseValue.ToString());\n         }\n     }\n     this.DC.SubmitChanges();\n     this.DC.Refresh(RefreshMode.OverwriteCurrentValues, att);\n }\n</code></pre>\n\n<p>When I looked at my output window while debugging, I could see that the Current Value matched the Database Value.  The "Original Value" was always the culprit.  That was the value read by the data context before applying the update.</p>\n\n<p>Thanks to MarceloBarbosa for the inspiration.</p>\n'}, {'answer_id': 68623818, 'author': 'Scott M', 'author_id': 5627488, 'author_profile': 'https://Stackoverflow.com/users/5627488', 'pm_score': 0, 'selected': False, 'text': "<p>I know this is an older post, but the issue can still be problematic today. I wanted to share my experience with this; as the solution for me was slightly different than the accepted answer. The accepted answer however did lead me to resolve my issue so thank you!</p>\n<p>In my case, I had an update trigger that would auto-insert a row into a status history table anytime the status changed on a row in a table (SQL Server); based on a set of known codes. My history table had a NOT NULL attribute for the status ID column, and my INSERT statement didn't take into account that a previously unknown code might slip through; thereby causing the row to insert to fail.</p>\n<p>So the moral of the story is in addition to checking your data models, be sure to review any triggers you have defined as that too will result in a &quot;row not found or changed&quot; error.</p>\n<p>Hope this helps someone else down the line; thanks all!</p>\n"}, {'answer_id': 71927264, 'author': 'Pablo Acosta', 'author_id': 18865518, 'author_profile': 'https://Stackoverflow.com/users/18865518', 'pm_score': 0, 'selected': False, 'text': '<p>I had the same problem when inserting data and then wanting to modify or delete them in the same form, the solution I found to this was the following:</p>\n<pre><code>db.Refresh(System.Data.Linq.RefreshMode.KeepChanges, employee);\n</code></pre>\n<p>db = is your connection variable as you might imagine, and employee would be the variable you would be using for your table.</p>\n'}]
['https://Stackoverflow.com/questions/45045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2723/']