asp.net - linq to sql 简单问题

发布于 2024-10-12 00:18:11 字数 377 浏览 2 评论 0原文

有谁知道我在从数据库获取数据时做错了什么。

我有以下代码

            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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情绪操控生活 2024-10-19 00:18:11

我不知道 ViewData 是什么,但您需要注意,Linq to SQL 查询在将它们分配给某个变量后不会立即执行。这称为延迟加载,它的意思是当您尝试对其进行操作时(例如,当您尝试迭代结果或某物时),您将获得数据。

你想要的是:

var a = (from p in db.test3s
        where p.ID == '1'
        select p.PostID).First();

这将为你带来第一个结果。如果你想获得一组结果,你可以调用 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:

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.

冬天的雪花 2024-10-19 00:18:11

尝试

if(a.Any())
   ViewData["a"] = a.First();

Try

if(a.Any())
   ViewData["a"] = a.First();
彡翼 2024-10-19 00:18:11

您需要在值可用之前迭代结果。 Linq2Sql 不知道您的查询只会返回一行(尽管您可能知道这一点)。因此,您可以这样做:

ViewData["a"] = db.test3s.First(t => t.Id == 1).PostID;

这将确保只有一个结果,并且将 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:

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.

抽个烟儿 2024-10-19 00:18:11

在您的示例中,a 的类型为IQueryable。它就像一个项目列表(但延迟执行)。您应该使用一些选择器检索具体项目:First()FirstOrDefault()Single()SingleOrDefault()< /code> 等等(具体情况取决于你的需要)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文