Entity Framework getting an sql connection

后端 未结 8 2003
栀梦
栀梦 2021-02-08 02:16

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 con

8条回答
  •  星月不相逢
    2021-02-08 02:26

    You could use the following as well. I wanted to inject some Dapper.NET into a existing project that already had Entity framework entity context so I created the following:

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

    Called using

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

提交回复
热议问题