从LINQ到SQL的DataContext的SubmitChanges之前检索对象 [英] Retrieve object from LINQ-to-SQL DataContext before SubmitChanges
问题描述
我插入一个新的对象到LINQ到SQL的DataContext不调用的SubmitChanges()尚未:
I insert a new object into LINQ-to-SQL DataContext without calling SubmitChanges() yet:
MyDataContext db = new MyDataContext();
MyObject newObject = new MyObject()
{
Id = 1,
Name = "MyName"
};
db.MyObjects.InsertOnSubmit(newObject);
现在在我的code另一个地方,我想取出这个新的对象,即使它是不是在数据库中呢。所以,我通过同一DataContext的实例有,因为我相信,新的对象缓存里面。现在我想找回它。但是,这并不工作:
Now in another place in my code I want to retrieve this new object, even though it is not in the database yet. So I pass the same DataContext instance there, because I believe that the new object is cached inside it. And now I want to retrieve it. But this doesn't work:
MyObject newObject = db.MyObjects.Where(o => o.Id == 1).SingleOrDefault();
我怎么做我想要什么?这可能吗?
How can I do what I want? Is that possible?
推荐答案
尝试:
db.MyObjects.SingleOrDefault(o => o.Id == 1);
您会认为这将是相同的,但看到这两个连接问题:
You'd think this would be the same, but see these two connect issues:
- LINQ-to-SQL doesn't use cache for lookup
- LINQ-to-SQL still roundtrips for ID lookups (3.5SP1)
如果不工作,我知道。单(O => o.Id == 1)
3.5 SP1中工作(我不知道知道如果我试图 .SingleOrDefault(preD)
)。显然,。凡(O => o.Id == 1)。单()
被固定在4.0 - 再次,我没有尝试过。凡(preD).SingleOrDefault()
。
If that doesn't work, I know that the .Single(o => o.Id == 1)
works in 3.5 SP1 (I don't know if I tried .SingleOrDefault(pred)
). Apparently the .Where(o => o.Id == 1).Single()
is fixed in 4.0 - again, I haven't tried .Where(pred).SingleOrDefault()
.
这篇关于从LINQ到SQL的DataContext的SubmitChanges之前检索对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!