实体框架得到一个SQL连接 [英] Entity Framework getting an sql connection

查看:176
本文介绍了实体框架得到一个SQL连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

闭幕实体框架和<一个明确连接的光HREF =http://msdn.microsoft.com/en-us/library/bb738582%28v=vs.90%29.aspx> http://msdn.microsoft.com/en-us/library/bb738582% 28V = VS.90%29.aspx 看来我应该使用上下文来创建连接,而不是做以下

In the light of Closing connections explicitly in Entity Framework and http://msdn.microsoft.com/en-us/library/bb738582%28v=vs.90%29.aspx it seems that I should be using the context to create connections rather than doing the following

using (SqlConnection con = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=(local)"))
{
    ...
}

我的理解是,我会


  • 摆脱连接字符串

  • 的利用内置到EF连接池

但我怎么获得通过上下文的SQL连接?

But how do I acquire an SQL connection through the context?

推荐答案

我发现了神奇之处在于 ExecuteStoreCommand()

I found out that the magic lies in ExecuteStoreCommand()

  new AdventureEntities().ExecuteStoreCommand(
        @"    UPDATE Users
              SET lname = @lname 
              WHERE Id = @id",
        new SqlParameter("lname", lname), new SqlParameter("id", id));



那就没有必要明确地连接,实际上所取得的代码很多清洁器。上面的单行全部换成下面的代码使用(SqlConnection的CON =新的SqlConnection

Then there is no need for an explicit Connection, it actually made the code a lot cleaner. The one-liner above replaced all of the following code

  using (SqlConnection con = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=(local)"))
  {
    con.Open();
    using (SqlCommand cmd = con.CreateCommand())
    {
      cmd.CommandText = @"
          UPDATE Users
          SET lname = @lname 
          WHERE Id = @id";
      cmd.Parameters.AddWithValue("lname", lname);
      cmd.Parameters.AddWithValue("id", id);
      cmd.ExecuteNonQuery();
    }
  }

这篇关于实体框架得到一个SQL连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆