Get the Entity Framework Connection String

前端 未结 11 977
迷失自我
迷失自我 2021-01-31 02:27

We use Entity Framework 5, but have a requirement to ALSO use a normal database connection from the application for some custom SQL we need to perform.

So, I am creating

相关标签:
11条回答
  • 2021-01-31 03:01

    //Entity Framework 5

    myContext.Database.Connection.ConnectionString
    

    //Entity Framework 6

    myContext.Database.Connection.ConnectionString
    

    //Entity Framework Core 1

    myContext.Database.GetDbConnection().ConnectionString
    
    0 讨论(0)
  • 2021-01-31 03:02

    I had this problem too, to solve the problem you can do this:

            SqlConnection con = context.Database.Connection as SqlConnection;
            SqlCommand command = new SqlCommand(sql, con);
            con.Open();
    
            SqlDataReader reader = command.ExecuteReader();
            while (reader.HasRows)
            {
                while (reader.Read())
                {
                    //read your fields
                }
    
                reader.NextResult();
            }
    
            con.Close();
    
    0 讨论(0)
  • 2021-01-31 03:03

    Here is a generic way of getting the connection string:

       public string GetConnString<T>(T ent)
                where T : ObjectContext
            {
                EntityConnection ec = (EntityConnection)ent.Connection;
                SqlConnection sc = (SqlConnection)ec.StoreConnection;
                return sc.ConnectionString;
            }
    

    Then to use it would be:

     MyEntities ent = new MyEntities();
     String ConnString = GetConnString(ent);
    
    0 讨论(0)
  • 2021-01-31 03:04

    In current versions of EF you can find the property here: dbContext.Database.TransactionManager.ConnectionString

    0 讨论(0)
  • 2021-01-31 03:05

    Do you mean, can you use a SqlConnection with your EF DbContext?

    The DbContext class has a constructor where you can pass in a SqlConnection, and then tell EF whether or not it owns it.

    var YourContext = new YourContext(SqlConnection, true);
    
    0 讨论(0)
  • 2021-01-31 03:15

    You can get the connectionstring used by EF by using the following:

    MyDbContext.Database.Connection.ConnectionString
    

    Or as mark says you can initalise the context with a sqlconnection

    0 讨论(0)
提交回复
热议问题