简体   繁体   English

从强类型数据集中返回一行

[英]Return a single row from a Strongly Typed Dataset

In my C# ASP.Net project I am using a xsd dataset to link to my database. 在我的C#ASP.Net项目中,我使用xsd数据集链接到我的数据库。 I want to create a function return a single row from the strongly typed datatable but I'm running into a little difficulty doing this in C#. 我想创建一个从强类型数据表返回一行的函数,但是在C#中这样做有点麻烦。 I have previously done this in VB.Net successfully using the code: 我以前在VB.Net中成功使用以下代码完成了此操作:

Public Function dr() As DataSet1.UsersRow
    Dim ta As New DataSet1TableAdapters.UsersTableAdapter
    Dim dt As DataSet1.UsersDataTable = ta.GetData
    Return dt.Rows(0)
End Function

My C# version of the code is: 我的代码的C#版本是:

public DataSet1.UsersRow dr()
{
    DataSet1TableAdapters.UsersTableAdapter ta = new DataSet1TableAdapters.UsersTableAdapter();
    DataSet1.UsersDataTable dt = ta.GetData;
    return dt.Rows(0);
}

I get the error Cannot implicitly convert type 'System.Data.DataRow' to 'MyProject.DataSet1.UsersRow'. 我收到错误“无法将类型'System.Data.DataRow'隐式转换为'MyProject.DataSet1.UsersRow'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)

How can I return my strongly typed row in C# 如何在C#中返回我的强类型行

您应该能够使用对其进行强类型化

dt[0];

The solution was to explicitly convert the Rows item as I returned it: 解决方案是在返回行时显式转换Rows项:

public DataSet1.UsersRow dr()
{
    DataSet1TableAdapters.UsersTableAdapter ta = new DataSet1TableAdapters.UsersTableAdapter();
    DataSet1.UsersDataTable dt = ta.GetData();
    return (DataSet1.UsersRow)dt.Rows(0);
}

A more efficient solution would be to add a query to the tableadapter along the lines of SELECT TOP 1 .. . 一种更有效的解决方案是按照SELECT TOP 1 ...的方式向tableadapter添加查询。 FROM users, (or more generally, add a WHERE clause to return the required row.) That way you are not pulling the entire table back just to retrieve one row. FROM用户,(或更一般而言,添加WHERE子句以返回所需的行。)这样,您就不会拉回整个表,而只是检索一行。

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

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