asp.net - linq to sql 简单问题
有谁知道我在从数据库获取数据时做错了什么。
我有以下代码
var a = from p in db.test3s
where p.ID == '1'
select p.PostID;
ViewData["a"] = a;
并且在 .aspx 文件中 ViewData["a"] 向我显示:
SELECT [t0].[PostID] FROM [dbo].[test3] AS [t0] WHERE [t0].[ID] = @p0
...而不是(某些)整数。
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"] shows me this:
SELECT [t0].[PostID] FROM [dbo].[test3] AS [t0] WHERE [t0].[ID] = @p0
...instead of an (some) integer number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不知道 ViewData 是什么,但您需要注意,Linq to SQL 查询在将它们分配给某个变量后不会立即执行。这称为延迟加载,它的意思是当您尝试对其进行操作时(例如,当您尝试迭代结果或某物时),您将获得数据。
你想要的是:
这将为你带来第一个结果。如果你想获得一组结果,你可以调用 ToList()、ToArray() 或类似的方法。
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:
This will get you first result. If you want to get set of results you can call ToList(), ToArray() or something like that.
尝试
Try
您需要在值可用之前迭代结果。 Linq2Sql 不知道您的查询只会返回一行(尽管您可能知道这一点)。因此,您可以这样做:
这将确保只有一个结果,并且将
PostID
的值分配给您的视图数据。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:
Which will make sure that there is only one result, and that the value of
PostID
is assigned to your view data.在您的示例中,
a
的类型为IQueryable
。它就像一个项目列表
(但延迟执行)。您应该使用一些选择器检索具体项目:First()
、FirstOrDefault()
、Single()
、SingleOrDefault()< /code> 等等(具体情况取决于你的需要)
In your example
a
is of typeIQueryable<Int32>
. It'slike 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)