Returning datatable using entity framework

后端 未结 5 1519
南方客
南方客 2020-12-09 10:37

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 t

5条回答
  •  星月不相逢
    2020-12-09 11:12

    This solution is simple, very fast and easy to use.

    Create a DbContext extension:

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

    Examples:

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

提交回复
热议问题