简体   繁体   中英

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?

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.

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"; 

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