简体   繁体   English

asp.net-LINQ to sql简单问题

[英]asp.net - linq to sql simple question

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: 在.aspx文件中,ViewData [“ a”]向我展示了这一点:

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. 我不知道ViewData是什么,但您需要知道,将Linq to SQL查询分配给某个变量后不会立即执行它们。 It's called lazy loading, and what it means is that you will have your data when you will try to operate on it (eg 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. 如果要获取结果集,可以调用ToList(),ToArray()或类似的方法。

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). Linq2Sql不知道您的查询将只返回一行(尽管您可能知道)。 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. 这样可以确保只有一个结果,并且PostID的值已分配给您的视图数据。

In your example a is of type IQueryable<Int32> . 在您的示例中, aIQueryable<Int32>类型。 It's like a list of items (but with delayed execution). like a list of items (但执行延迟)。 You should retrieve concrete item using some of selectors: First() , FirstOrDefault() , Single() , SingleOrDefault() and so on (depends what you need in concrete situation) 您应该使用一些选择器来检索具体项目: First()FirstOrDefault()Single()SingleOrDefault()等等(取决于具体情况下的需求)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM