使用实体框架返回datatable [英] Returning datatable using entity framework
本文介绍了使用实体框架返回datatable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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));
//需要编写下面的代码来填充DataTable。
}
解决方案
感谢很多人。我解决了这是解决方案:
DataTable dt = new DataTable();
var context = new DataBaseContext();
var conn = context.Database.Connection;
var connectionState = conn.State;
try
{
using(context)
{
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)
{
throw ex;
}
finally
{
if(connectionState!= ConnectionState.Open)
conn.Close();
}
return dt;
I am using entity framework. There is one particular situation in my application where I have to use a stored procedure. Since there are a lot of SQL statements written in the SP, I don't want to re-write it in my C# code. I only need to get the result back in the form of a datatable. I have written a little bit of code but I am stuck at one point. Can someone complete the code below?
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.
}
解决方案
Thanks a lot guys. I solved it. Here is the solution:
DataTable dt = new DataTable();
var context = new DataBaseContext();
var conn = context.Database.Connection;
var connectionState = conn.State;
try
{
using (context)
{
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)
{
throw ex;
}
finally
{
if (connectionState != ConnectionState.Open)
conn.Close();
}
return dt;
这篇关于使用实体框架返回datatable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文