linq2sql: can't fetch object 2nd time
In my application one object is fetched from DB with query like this:
IList<MyObject> objects = GetContext()
.GetTable()
.Where(obj=>obj.ParentId==iParentId)
.ToList()
;
After getting from db data from 'objects' lists is copied into list of business objects. Later I need 开发者_如何转开发to update this object with new data from business entity. For this purpose I need to get 'DB entity' from database, update it's fields and call 'SubmitChanges()'.
The problem is that '2nd fetch from DB' doesn't work. The following query:
MyObject objectToBeUpdated = GetContext()
.GetTable()
.Where(obj=>obj.Id==iObjectId)
.SingleOrDefault()
;
returns null..
Q1. Why I get 'null' here? Can this be caused that I need to 'release' the 1st entity in some way? Or I need to remember the original entity (don't fetch it from DB again) and update it?
Q2. How to get entity 2nd time?
P.S. Actually, I would rather will on preventing 2nd fetch, but it would be good to know the reason what is wrong here.
Thanks a lot.
P.S. I'm using MSSQL 2005, VS2008, Linq2sql.
I guess it returns null becoz there's no record that satisfies your where clause. Since you call SingleOrDefault() it returns you the default object that's null. Instead if you call Single() you will get an exception. Double check you actually have records in the db that meet the condition
精彩评论