实体框架获取一个sql连接 [英] Entity Framework getting an sql connection

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

问题描述

鉴于在实体框架中显式关闭连接和 http://msdn.microsoft.com/en- us / library / bb738582%28v = vs90%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()

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

然后不需要显式Connection,它实际上使代码更加清洁。上面的一行替换了以下所有代码

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天全站免登陆