tags:

views:

176

answers:

2

I'm currently using a single query in two places to get a row from a database.

BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == ID
                 select p).Single();

The query is fine when retrieving the row to put data in to the text boxes, but it returns an error "Sequence contains no elements" when used to retrieve the row in order to edit it and put it back in to the database. I can't understand why it might find an appropriate row in one instance but not another.

(Using ASP.NET MVC and LINQ)

+3  A: 

Well, what is ID here? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:

var id = ID;
BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == id
                 select p).Single();

Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:

var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);
Marc Gravell
ID is a GUID passed in as an argument
A: 

Put a breakpoint on that line, or a Debug.Print before it, in both cases and see what ID contains.

Kyralessa
Did that and found that, for some reason, the ID and date are being passed as null\new(0000-0000) from the edit page.The page is strongly typed as BlogPost. On the edit page, I only have text boxes for the title and content, the ID and date aren't put on the page at all. Could this be the reason for it passing them as null\new?
Where were you expecting the ID to come from?
Kyralessa
In hind sight, I'm really not sure >_< Silly problem really.