Does anyone knows what am I doing wrong, while getting a data from db.
I have the following code
var a = from p in db.test3s
where p.ID == '1'
select p.PostID;
ViewData["a"] = a;
And in the .aspx file the ViewData["a"] sh开发者_如何学Goows me this:
SELECT [t0].[PostID] FROM [dbo].[test3] AS [t0] WHERE [t0].[ID] = @p0
...instead of an (some) integer number.
I don't know, what ViewData is, but you need to be aware, that Linq to SQL queries are not executed immediately after you assign them to some variable. It's called lazy loading, and what it means is that you will have your data when you will try to operate on it (e.g. when you will try to iterate over results or sth).
What you want is:
var a = (from p in db.test3s
where p.ID == '1'
select p.PostID).First();
This will get you first result. If you want to get set of results you can call ToList(), ToArray() or something like that.
Try
if(a.Any())
ViewData["a"] = a.First();
You need to iterate over the result before the values become available. Linq2Sql does not know that your query will only return one row (although you may know that). So you could do this instead:
ViewData["a"] = db.test3s.First(t => t.Id == 1).PostID;
Which will make sure that there is only one result, and that the value of PostID
is assigned to your view data.
In your example a
is of type IQueryable<Int32>
. It's like a list of items
(but with delayed execution). You should retrieve concrete item using some of selectors: First()
, FirstOrDefault()
, Single()
, SingleOrDefault()
and so on (depends what you need in concrete situation)
精彩评论