如何从C#中的SQL查询中检索数据集?

时间:2014-05-01 05:23:10

标签: c# sql dataset

我正在尝试从SQL查询中检索Dataset。我正在使用Edmx进行数据访问。如果我使用一个简单的存储过程来检索dataTable,那么该函数工作正常,当我尝试检索数据集时,我无法将SQL结果转换为数据集。

这是我的Sql

--Query For Retrieving LastUpdatedDate
select top 3 
    YP.utblYPBusinessInstanceInfoKeys.BusinessID,
    YP.utblYPBusinessInstanceInfoKeys.BusinessName,
    YP.utblYPBusinessInstanceInfoKeys.LastUpdatedByDate as GeneraliseDate
from  
    YP.utblYPBusinessInstanceInfoKeys
order by  
    GeneraliseDate desc

--Query For Retrieving Listing by CreatedDate
select top 3 
    YP.utblYPBusinessInstanceInfoKeys.BusinessID,
    YP.utblYPBusinessInstanceInfoKeys.BusinessName,
    YP.utblYPBusinessInstanceInfoKeys.CreatedByDate as GeneraliseDate
from  
    YP.utblYPBusinessInstanceInfoKeys
order by  
    GeneraliseDate desc

如何在C#中检索SQl结果中的数据集?

2 个答案:

答案 0 :(得分:1)

给定sql查询,将结果填充到数据集中的最简单方法是使用SqlDataAdapter类,它完成所有工作(您只需要提供查询和打开的连接,并填充数据集)。

在你的情况下,它将是:

string queryString1 = "select top 3 YP.utblYPBusinessInstanceInfoKeys.BusinessID,
                                    YP.utblYPBusinessInstanceInfoKeys.BusinessName,
                                    YP.utblYPBusinessInstanceInfoKeys.LastUpdatedByDate as GeneraliseDate
                       from  YP.utblYPBusinessInstanceInfoKeys
                       order by  GeneraliseDate desc"

string queryString2 = "select top 3 YP.utblYPBusinessInstanceInfoKeys.BusinessID,
                                    YP.utblYPBusinessInstanceInfoKeys.BusinessName,
                                    YP.utblYPBusinessInstanceInfoKeys.CreatedByDate as GeneraliseDate
                        from  YP.utblYPBusinessInstanceInfoKeys
                        order by  GeneraliseDate desc"

string queryString = queryString1 + Environment.NewLine + queryString2;


DataSet dataSet = new DataSet();

var connection = new SqlConnection("TODO:put connection string here");
connection.Open();
using(connection)
{
    SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection); 
    adapter.Fill(dataSet);
}

// here you go
foreach(DataTable table in dataSet.Tables)
{
    Console.WriteLine(table.Name);
}

答案 1 :(得分:0)

实体框架返回实体而不是数据表或数据集。 你可以使用ADO.net(SqlCommand,SqlAdapter,....) 或者通过使用.AsEnumerable()手动完成并将其填入新的数据表或数据集中!