使用entity framework返回数据表

我正在使用entity framework。 在我的应用程序中有一个特殊情况,我必须使用存储过程。 由于在SP中编写了很多SQL语句,我不想​​在我的C#代码中重写它。 我只需要以数据表的forms返回结果。 我写了一些代码,但我一度陷入困境。 有人可以填写下面的代码吗?

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. } 

非常感谢你们。 我解决了 这是解决方案:

 using (var context = new DataBaseContext()) { var dt = new DataTable(); var conn = context.Database.Connection; var connectionState = conn.State; try { if (connectionState != ConnectionState.Open) conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = "GetAvailableItems"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("jobCardId", 100525)); using (var reader = cmd.ExecuteReader()) { dt.Load(reader); } } } catch (Exception ex) { // error handling throw; } finally { if (connectionState != ConnectionState.Closed) conn.Close(); } return dt; } 

此示例将返回从EntityFramework选择数据的数据表对象。

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

 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; }); 

该解决方案简单,快速且易于使用。

创建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() ); } 

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

  DataSet GetDataSet(string sql, CommandType commandType, Dictionary 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; }