从 SQL Server 返回并使用单行查询的最有效方法?

发布于 2024-10-04 07:32:23 字数 541 浏览 0 评论 0原文

我使用 C# 和 SQL Server 从数据库获取数据并在页面加载时填充页面上的一些标签。这些信息来自 SQL 视图,该视图在一行中返回一大堆信息。例如:

SELECT 'car' AS Product, 12 As daysUntilEOM, '2010-01-01' AS LastHoliday, 23.7 AS Length

总是只返回 1 行

我的项目的其余部分正在使用 LINQ 和我最初开始走这条路,但是创建一个我只使用一次的对象有什么意义,将所有值作为键值对分配给对象,然后将它们重新分配给标签文本?似乎有很多毫无意义的编码。

使用数据读取器似乎也有同样的问题。

我能看到的最简单的解决方案(即最少的代码)是使用 dataAdapter 填充数据集并将数据集从 DAL 传递回页面,然后直接分配给标签。但对于单行数据,这似乎就像用卡车运载单个西红柿。

是否有像 ExecuteScalar 这样返回整行而不是仅第一列的东西? 或者,编写 DataAdapter 的简便性就足够了,我应该不再担心开销吗?

谢谢!

I am using c# and SQL Server to get data from the database and populate a few labels on a page on pageload. The information comes from a SQL view which returns a whole bunch of information in a single row. eg:

SELECT 'car' AS product, 12 As daysUntilEOM, '2010-01-01' AS LastHoliday, 23.7 AS Length

There will always be only 1 row returned

The rest of my project is using LINQ and I originally started going down that path, but what is the point of creating an object that I'm only going to use once off for this, assigning all the values into the object as key-value pairs, and then reassigning them out to the label texts? Seems a lot of pointless coding.

Using a datareader also seems to have the same problem.

The simplest solution (ie least code) I can see is to use a dataAdapter to fill a dataset and pass the dataset back from the DAL to the page and then do the assigning straight to the labels. But for a single row of data this seems to be like using a truck to carry a single tomato.

Is there something like ExecuteScalar that returns a whole row instead of just the first column?
Or should the ease of coding the DataAdapter just be enough and I should stop worrying about overhead?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

说不完的你爱 2024-10-11 07:32:23

您应该调用 ExecuteReader 并传递 CommandBehavior.SingleRow 标志。

为了避免耦合,您可以将 DataReader 转换为字典,如下所示:

return Enumerable.Range(0, reader.FieldCount)
                 .ToDictionary(reader.GetName, reader.GetValue);

You should call ExecuteReader and pass the CommandBehavior.SingleRow flag.

To avoid coupling, you can convert the DataReader into a dictionary, like this:

return Enumerable.Range(0, reader.FieldCount)
                 .ToDictionary(reader.GetName, reader.GetValue);
养猫人 2024-10-11 07:32:23

ExecuteScalar 返回标量值,而不是行。带有命令对象的 DataAdapter(可能还向存储过程提供参数而不是执行 sql 语句)就可以了。

ExecuteScalar returns a scalar value, not the row. DataAdapter with a command object (possibly also feeding a parameter to a stored proc rather than executing the sql statement) will be fine.

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