将DbContext方式转换为SqlCommand方式

时间:2016-11-16 08:35:07

标签: asp.net sql-server entity-framework asp.net-core

今天我有一个使用EF Core工作的应用程序,使用DbContext类,看起来像这样:

    public class RcoreContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=rCoreData.TestDb;Trusted_Connection=True;");
        }

        public DbSet<Hosts> Hosts { get; set; }
        public DbSet<Route> Route { get; set; }
    }

    public class Hosts
    {
        public int      HostsId  { get; set; }
        public string   Host     { get; set; }

        [NotMapped]
        public Dictionary<object, object> Datas { get; set; }

        public string   DatasJson { get { return JsonConvert.SerializeObject(Datas); } set { Datas = JsonConvert.DeserializeObject<Dictionary<object, object>>(value); } }
    }

    public class Route
    {
        public int                          RouteId     { get; set; }
        public int                          HostId      { get; set; }
        public string                       RealRoute   { get; set; }
        public string                       alias       { get; set; }
    }

我非常喜欢这种方式,因为请求返回基于现有的类(此代码中为HostsRoute)。

使用SqlCommand方式似乎更舒服(它似乎更像PHP),但似乎将条目返回为object。 (我读过this article

我想知道是否可以在两种方式之间进行混合并将请求作为StoredProcedure发送,如SqlCommand,但仍然基于请求返回的现有类。

由于

3 个答案:

答案 0 :(得分:3)

如果你想在EF中使用ADO.NET,你只需要获取当前的连接字符串并创建sqlcommand,如下所示:

using (var context = new RcoreContext())
{
   // creates a Command 
   var command = context.Database.Connection.CreateCommand();
   command.CommandType = commandType;
   command.CommandText = sql;

   using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.WriteLine(reader.GetValue(i));
        }
        Console.WriteLine();
        }
    }
}

如果您只想执行sql或存储过程,您也可以在EF

中使用以下内容
 _dbContext.Database.ExecuteSqlCommand(sql, parameters);
_dbContext.Database.SqlQuery<TEntity>(sql, parameters);

答案 1 :(得分:0)

    using (var connection = context.Database.GetDbConnection())
    using (var command = context.Database.GetDbConnection().CreateCommand())
    { 
       command.CommandText = string.Format(sqlQuery, id);
       connection.Open();
       using (var reader = command.ExecuteReader()){}
    }

答案 2 :(得分:0)

using (var connection = new SqlConnection(_dbContext.Database.Connection.ConnectionString))
using (var cmd = new SqlCommand())
{
      cmd.Connection = connection;
      cmd.CommandText = "your query here";
      cmd.CommandType = CommandType.Text;

      cmd.Parameters.Add("@param1", SqlDbType.Int);

      cmd.Connection.Open();
      cmd.ExecuteNonQuery();
}