EF扩展方法

为君一笑 提交于 2020-02-27 20:06:11

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!