EF是微软提供的数据库ORM框架,集众家之所长,方便在Winform中使用,可以方便的转换成DataTable,代码如下:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF.Winfrom.Context
{
public static class EFExtendMethod
{
public static DataTable SqlQueryToDataTable(this Database db, string sql, CommandType type = CommandType.Text, params SqlParameter[] param)
{
DataTable ret_dt = new DataTable();
SqlConnection conn = db.Connection as SqlConnection;
if (conn == null)
{
conn = new SqlConnection(db.Connection.ConnectionString);
}
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = type;
if (param != null && param.Length > 0)
{
foreach (SqlParameter p in param)
{
cmd.Parameters.Add(p);
}
}
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ret_dt);
conn.Close();
return ret_dt;
}
catch (Exception ex)
{
conn.Close();
return ret_dt;
}
}
public static DataTable SqlQueryToDataTable(this Database db, string sql, params SqlParameter[] param)
{
return SqlQueryToDataTable(db, sql, CommandType.Text, param);
}
}
}
来源:oschina
链接:https://my.oschina.net/stupidpotato/blog/3176259