Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq cannot find inserted record before submitchanges

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 have not called SubmitChanges.

Why does bExists come back as false? Shouldn't Linq be able to see the inserted record?

like image 800
Jack Avatar asked Jan 05 '12 03:01

Jack


2 Answers

See Linq cannot write values into DB, if submitchanges() not called.

And for second question, Yes, Linq cache objects before submitting. We can also get records which are in cache but not Submitted to database.

As you inserted record above, we can get above record from cache of datacontext as below:

First Get changeset from DataContext as:

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

After it, extract your record form Changeset:

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

You will get MyRecord with Title as "test", Which you Inserted.

Hope this will Help.

like image 144
Pankaj Tiwari Avatar answered Oct 22 '22 00:10

Pankaj Tiwari


I believe that

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

is an SQL query that the SQL server returns the result. So if you have not submitted, then the DB does not know anything about:

MyRecord R = new MyRecord(); 
R.Title = "test"; 
like image 35
joe_coolish Avatar answered Oct 21 '22 23:10

joe_coolish