【问题标题】:Entity Framework getting an sql connection实体框架获取 sql 连接
【发布时间】:2011-03-12 22:50:14
【问题描述】:

鉴于Closing connections explicitly in Entity Frameworkhttp://msdn.microsoft.com/en-us/library/bb738582%28v=vs.90%29.aspx 似乎我应该使用上下文来创建连接而不是执行以下操作

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

我的理解是我会

  • 摆脱连接字符串
  • 利用 EF 中内置的连接池

但是如何通过上下文获取 SQL 连接呢?

【问题讨论】:

标签: c# entity-framework


【解决方案1】:

在 EF5(已更改为 EF6)中,以下将返回连接:

var connection = ((EntityConnection)context.Connection).StoreConnection;

如果您以正确的方式使用 EF,您可能永远不需要获取内部数据库连接。

【讨论】:

  • context.Connection 自 EF6 以来已被删除
  • @RomanPokrovskij 在 EF6 中你可以使用 context.Database.Connection
【解决方案2】:

我发现神奇在于 ExecuteStoreCommand()

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

那么就不需要显式连接了,它实际上使代码更简洁。上面的一行代码替换了以下所有代码

  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,甚至还有更好的方法。检查 ObjectStateManager、GetObjectStateEntry、ObjectStateEntry 和 SetModifiedProperty。
  • 由于问题在问题中搞砸了,它被删除了。你能把答案放在这里,我会接受的
  • 我已经在那里投票支持重新开放,所以如果其他有高代表的用户我会等待。在做出重复回答之前也会投票。
【解决方案3】:

我使用下一个代码来获取连接(实体框架 5.0):

var connection = Context.Database.Connection;

【讨论】:

    【解决方案4】:
    var efConnectionStringBuilder = new EntityConnectionStringBuilder(efConnectionString);
    string sqlConnectionString = efConnectionStringBuilder.ProviderConnectionString;
    

    【讨论】:

      【解决方案5】:

      如果 EF 连接字符串存储在您的 Web 配置文件中,您可以使用以下代码将其分配给 SQL 数据源:

                  var connString = ConfigurationManager.ConnectionStrings["MyDataEntities"].ConnectionString;
                  EntityConnection ec = new EntityConnection(connString);
                  var storeConnect = ec.StoreConnection;
      
                  SqlDataSource1.ConnectionString = storeConnect.ConnectionString;
      

      【讨论】:

        【解决方案6】:

        我相信在 EF6 中创建 SqlConnection 的最简单方法是执行以下操作:

        DBContext context = new DBContext();
        SqlConnection sqlconn = new SqlConnection(context.Database.Connection.ConnectionString);
        

        【讨论】:

          【解决方案7】:

          您也可以使用以下内容。我想将一些 Dapper.NET 注入到已经有 Entity 框架实体上下文的现有项目中,所以我创建了以下内容:

          public class EFConnectionAccessor : IDisposable
          {
              private readonly SqlConnection sqlConnection;
              private readonly MyEntities entities;
          
              public EFConnectionAccessor()
              {
                  entities = new MyEntities();
          
                  var entityConnection = entities.Connection as EntityConnection;
          
                  if (entityConnection != null)
                  {
                      sqlConnection = entityConnection.StoreConnection as SqlConnection;
                  }
              }
          
              public SqlConnection connection
              {
                  get
                  {
                      sqlConnection.Open();
                      return sqlConnection;
                  }
              }
          
              public void Dispose()
              {
                  sqlConnection.Close();
                  sqlConnection.Dispose();
                  entities.Dispose();
              }
          }
          

          调用使用

          using (SqlConnection sqlConnection = new EFConnectionAccessor().connection)
          {
           // ADO.NET CODE HERE - Or in my case dapper.net
          }
          

          【讨论】:

            【解决方案8】:

            DataContext 将允许您直接从 DataContext 引用中调用实体对象,从而抽象出底层连接物流的所有细节。

            【讨论】:

            • 是的,但是我想在不先读取实体的情况下触发 UPDATE 语句 - 因此我需要一个 SQLConnection
            • 可以说它是自动连接的,您可以在 EF 连接时触发更新及其然后。(除非您在此之前执行其他操作)
            • 不确定我理解你的 Aviatrix,请举个例子回答,我会为你投票 :)
            • @Carlo:是你删除了EntityCommand的问题吗?我只是给你写了两种方法来实现你想要的,但现在我的答案被你的问题删除了......
            • 抱歉,不知道出了什么问题。请在此处重新发布(凭记忆?)不知道如何取消删除它
            猜你喜欢
            • 2012-10-11
            • 1970-01-01
            • 2015-09-30
            • 2020-01-13
            • 2011-07-29
            • 1970-01-01
            • 1970-01-01
            • 2017-06-15
            • 1970-01-01
            相关资源
            最近更新 更多