Get object from LINQ-to-SQL DataContext before SubmitChanges

I insert a new object into the LINC-to-SQL DataContext without calling the SubmitChanges () function:

MyDataContext db = new MyDataContext();
MyObject newObject = new MyObject() 
{
   Id = 1,
   Name = "MyName"
};
db.MyObjects.InsertOnSubmit(newObject);

Now elsewhere in my code I want to get this new object, although it is not already in the database. Therefore, I am passing the same instance of the DataContext because I believe that the new object is cached inside it. And now I want to get it. But this does not work:

MyObject newObject = db.MyObjects.Where(o => o.Id == 1).SingleOrDefault();

How can I do what I want? Is it possible?

+3
source share
1 answer

Try:

db.MyObjects.SingleOrDefault(o => o.Id == 1);

You would think it would be the same thing, but look at these two communication problems:

, , .Single(o => o.Id == 1) 3.5 SP1 ( , .SingleOrDefault(pred)). -, .Where(o => o.Id == 1).Single() 4.0 - , .Where(pred).SingleOrDefault().

+1

Source: https://habr.com/ru/post/1707467/


All Articles