Linq cannot find inserted record before submission

I have this bit of code:

LinqDataContext ctx; MyRecord R = new MyRecord(); R.Title = "test"; ctx.AllRecords.InsertOnSubmit(R); bool bExists = ctx.AllRecords.Any(r => r.Title == "test"); 

Note. I did not call SubmitChanges.

Why do bExists return as false? Can't Linq be able to see the inserted record?

+8
c # linq linq-to-sql
source share
2 answers

See Linq cannot write values ​​to the database if subordinates () are not called.

And for the second question, Yes, Linq cache objects before sending. We can also get entries that are in the cache but not transferred to the database.

When you inserted the record above, we can get the above records from the datacontext cache, as shown below:

First get the changeset from the DataContext as:

 System.Data.Linq.ChangeSet MySet = ctx.GetChangeSet(); 

After that, extract your registration form. Changes:

 MyRecord b = (MyRecord )MySet.Inserts.Last(); 

You will receive MyRecord with the title as the β€œtest” that you entered.

Hope this helps.

+8
source share

I think that

 bool bExists = ctx.AllRecords.Any(r => r.Title == "test"); 

is the SQL query returned by the SQL server. So if you haven’t submitted, then DB knows nothing about:

 MyRecord R = new MyRecord(); R.Title = "test"; 
+1
source share

All Articles