Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用实体框架返回数据表_C#_Entity Framework_Ado.net Entity Data Model - Fatal编程技术网

C# 使用实体框架返回数据表

C# 使用实体框架返回数据表,c#,entity-framework,ado.net-entity-data-model,C#,Entity Framework,Ado.net Entity Data Model,我使用的是实体框架。在我的应用程序中有一种特殊情况,我必须使用存储过程。由于SP中编写了大量SQL语句,因此我不想在C#代码中重新编写它。我只需要以数据表的形式返回结果。我已经写了一点代码,但有一点被卡住了。有人能完成下面的代码吗 using (dbContext.Database.Connection) { dbContext.Database.Connection.Open(); DbCommand cmdItems= dbContext.Database.Connection.Create

我使用的是实体框架。在我的应用程序中有一种特殊情况,我必须使用存储过程。由于SP中编写了大量SQL语句,因此我不想在C#代码中重新编写它。我只需要以数据表的形式返回结果。我已经写了一点代码,但有一点被卡住了。有人能完成下面的代码吗

using (dbContext.Database.Connection)
{
dbContext.Database.Connection.Open();
DbCommand cmdItems= dbContext.Database.Connection.CreateCommand();
cmdItems.CommandText = "GetAvailableItems";
cmdItems.CommandType = CommandType.StoredProcedure;
cmdItems.Parameters.Add(new SqlParameter("jobCardId", 100525));
//Need to write code below to populate a DataTable.
}

谢谢大家。我解决了。以下是解决方案:

使用(var context=new DataBaseContext())
{
var dt=新数据表();
var conn=context.Database.Connection;
变量连接状态=连接状态;
尝试
{
if(connectionState!=connectionState.Open)conn.Open();
使用(var cmd=conn.CreateCommand())
{
cmd.CommandText=“GetAvailableItems”;
cmd.CommandType=CommandType.storedProcess;
cmd.Parameters.Add(新的SqlParameter(“jobCardId”,100525));
使用(var reader=cmd.ExecuteReader())
{
dt.负载(读卡器);
}
}
}
捕获(例外情况除外)
{
//错误处理
投掷;
}
最后
{
如果(connectionState!=connectionState.Closed)连接关闭();
}
返回dt;
}

此示例将返回一个从
EntityFramework
选择数据的
datatable
对象

我相信这是实现这一目标的最佳方案。然而,这个解决方案的问题是,每个记录都是枚举的。您可能希望先筛选列表,然后从列表中运行此操作以避免出现这种情况

DataTable dt = new DataTable();
(from rec in database.Table.AsEnumerable()
                     select new
                     {
                         id = rec.id,
                         name = rec.Name
                         //etc
                     }).Aggregate(table, (dt, r) =>
                     {
                         dt.Rows.Add(r.id, r.Name);
                         return dt;
                     });

只是改进了以前的解决方案,现在包括通用参数(不是特定于SQL Server)和多个结果集支持:

    DataSet GetDataSet(string sql, CommandType commandType, Dictionary<string, Object> parameters)
    {
        // creates resulting dataset
        var result = new DataSet();

        // creates a data access context (DbContext descendant)
        using (var context = new MyDbContext())
        {
            // creates a Command 
            var cmd = context.Database.Connection.CreateCommand();
            cmd.CommandType = commandType;
            cmd.CommandText = sql;

            // adds all parameters
            foreach (var pr in parameters)
            {
                var p = cmd.CreateParameter();
                p.ParameterName = pr.Key;
                p.Value = pr.Value;
                cmd.Parameters.Add(p);
            }

            try
            {
                // executes
                context.Database.Connection.Open();
                var reader = cmd.ExecuteReader();

                // loop through all resultsets (considering that it's possible to have more than one)
                do
                {
                    // loads the DataTable (schema will be fetch automatically)
                    var tb = new DataTable();
                    tb.Load(reader);
                    result.Tables.Add(tb);

                } while (!reader.IsClosed);
            }
            finally
            {
                // closes the connection
                context.Database.Connection.Close();
            }
        }

        // returns the DataSet
        return result;
    }
DataSet GetDataSet(字符串sql、命令类型CommandType、字典参数)
{
//创建结果数据集
var result=新数据集();
//创建数据访问上下文(DbContext子体)
使用(var context=new MyDbContext())
{
//创建一个命令
var cmd=context.Database.Connection.CreateCommand();
cmd.CommandType=CommandType;
cmd.CommandText=sql;
//添加所有参数
foreach(参数中的var pr)
{
var p=cmd.CreateParameter();
p、 ParameterName=公共密钥;
p、 价值=公共价值;
cmd.Parameters.Add(p);
}
尝试
{
//执行
context.Database.Connection.Open();
var reader=cmd.ExecuteReader();
//循环遍历所有结果集(考虑到可能有多个结果集)
做
{
//加载数据表(将自动获取架构)
var tb=新数据表();
tb.Load(读卡器);
结果.表格.添加(tb);
}而(!reader.IsClosed);
}
最后
{
//关闭连接
context.Database.Connection.Close();
}
}
//返回数据集
返回结果;
}

此解决方案简单、快速且易于使用

创建DbContext扩展:

using System.Data;
using System.Data.Common;
using System.Data.Entity;
..
..
public static class DbContextExtensions
{
    public static DataTable DataTable(this DbContext context, string sqlQuery)
    {
        DbProviderFactory dbFactory = DbProviderFactories.GetFactory(context.Database.Connection);

        using (var cmd = dbFactory.CreateCommand())
        {
            cmd.Connection = context.Database.Connection;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sqlQuery;
            using (DbDataAdapter adapter = dbFactory.CreateDataAdapter())
            {
                adapter.SelectCommand = cmd;

                DataTable dt = new DataTable();
                adapter.Fill(dt);

                return dt;
            }
        }
    }
}
示例:

using (MyDbContext db = new MyDbContext())
{
    string query = db.Students.Where(o => o.Age > 20).ToString();

    DataTable dataTable = db.DataTable(query);

    ..

    DataTable dt = db.DataTable(
                         (  from o in db.Studets
                            where o.Age > 20
                            select o
                         ).ToString()
                    );
}

我只是把答案弄混了。此代码运行动态查询并将结果转换为字典列表

public List < Dictionary < string,object >> DataTableToDictionaryList(DataTable table) {
    List < Dictionary < string,
    object >> parentRow = new List < Dictionary < string,
    object >> ();
    Dictionary < string,
    object > childRow;
    foreach(DataRow row in table.Rows) {
        childRow = new Dictionary < string,
        object > ();
        foreach(DataColumn col in table.Columns) {
            childRow.Add(col.ColumnName, row[col]);
        }
        parentRow.Add(childRow);
    }
    return (parentRow);
}

List < Dictionary < string,object >> RunDynamicQuery(string sql, Dictionary < string, Object > parameters = null, int resultSet = 0, CommandType commandType = CommandType.Text) {
    // creates resulting dataset
    var resultDataSet = new DataSet();

    // creates a data access context (DbContext descendant)
    using(var context = new DataDbContext()) {
        // creates a Command 
        var conn = context.Database.Connection;
        var cmd = conn.CreateCommand();
        cmd.CommandType = commandType;
        cmd.CommandText = sql;

        if (parameters != null) {
            // adds all parameters
            foreach(var pr in parameters) {
                var p = cmd.CreateParameter();
                p.ParameterName = pr.Key;
                p.Value = pr.Value;
                cmd.Parameters.Add(p);
            }
        }

        try {
            // executes
            if (conn.State != ConnectionState.Open) {
                conn.Open();
            }

            var reader = cmd.ExecuteReader();

            // loop through all resultsets (considering that it's possible to have more than one)
            int currentResultSet = -1;
            do {
                currentResultSet++;
                //skip lower resultsets
                if (resultSet > currentResultSet) {
                    continue;
                }

                // loads the DataTable (schema will be fetch automatically)
                var tb = new DataTable();
                tb.Load(reader);
                resultDataSet.Tables.Add(tb);
                //make sure to get only one result set
                break;
            } while (! reader . IsClosed );

        }
        finally {
            // closes the connection
            context.Database.Connection.Close();
        }
    }

    return DataTableToDictionaryList(resultDataSet.Tables[0]);
}
public List>DataTableToDictionaryList(DataTable表){
列表<字典<字符串,
对象>>父行=新列表<字典<字符串,
对象>>();
字典子行;
foreach(table.Rows中的DataRow行){
childRow=新字典<字符串,
对象>();
foreach(table.Columns中的数据列col){
添加(列名称,行[col]);
}
parentRow.Add(childRow);
}
返回(parentRow);
}
List>RunDynamicQuery(string-sql,Dictionaryparameters=null,int-resultSet=0,CommandType-CommandType=CommandType.Text){
//创建结果数据集
var resultDataSet=新数据集();
//创建数据访问上下文(DbContext子体)
使用(var context=new DataDbContext()){
//创建一个命令
var conn=context.Database.Connection;
var cmd=conn.CreateCommand();
cmd.CommandType=CommandType;
cmd.CommandText=sql;
if(参数!=null){
//添加所有参数
foreach(参数中的var pr){
var p=cmd.CreateParameter();
p、 ParameterName=公共密钥;
p、 价值=公共价值;
cmd.Parameters.Add(p);
}
}
试一试{
//执行
如果(连接状态!=连接状态打开){
conn.Open();
}
var reader=cmd.ExecuteReader();
//循环遍历所有结果集(考虑到可能有多个结果集)
int currentResultSet=-1;
做{
currentResultSet++;
//跳过较低的结果集
如果(结果集>当前结果集){
继续;
}
//加载数据表(将自动获取架构)
var tb=新数据表();
tb.Load(读卡器);
resultDataSet.Tables.Add(tb);
//确保只获得一个结果集
打破
}而(!reader.IsClosed);
}
最后{
//关闭连接
context.Database.Connection.Close();
}
}
返回DataTableToDictionaryList(resultDataSet.Tables[0]);
}

使用提到的链接我首先使用的是代码,我没有re的实体