Get the Entity Framework Connection String

前端 未结 11 979
迷失自我
迷失自我 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:15

    Here's how to get the connection string in EF 5, EF 6 and EF Core 1/EF 7.

    //Entity Framework 5
    myContext.Database.Connection.ConnectionString
    //Entity Framework 6
    myContext.Database.Connection.ConnectionString
    //Entity Framework Core 1
    myContext.Database.GetDbConnection().ConnectionString
    

    For more details see - http://nodogmablog.bryanhogan.net/2016/04/entity-framework-checking-the-connection-string-of-your-context/

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

    Yes you can.

    See here for 3 options.

    1 - use separate connection string for each

    2 - extract it from your entity object (this is what i think you want)

    3 - use the entity object to execute your custom SQL

    Here's how to do nr 2:

    using System.Data.EntityClient;
    using System.Data.SqlClient;
    ...
    private string GetADOConnectionString()
    {
        SalesSyncEntities ctx = new SalesSyncEntities(); //create your entity object here
        EntityConnection ec = (EntityConnection)ctx.Connection;
        SqlConnection sc = (SqlConnection)ec.StoreConnection; //get the SQLConnection that your entity object would use
        string adoConnStr = sc.ConnectionString;
        return adoConnStr;
    }
    
    0 讨论(0)
  • 2021-01-31 03:16

    Hope it helps..

        private readonly ApplicationDbContext _applicationDbContext;
        string connectionString = string.Empty;
    
        public CommonService(ApplicationDbContext applicationDbContext)
        {
            _applicationDbContext = applicationDbContext;
            connectionString = _applicationDbContext.Database.GetDbConnection().ConnectionString;
        }
    
    0 讨论(0)
  • 2021-01-31 03:21

    even in EF3 you can use EntityConnectionStringBuilder.

    EntityConnectionStringBuilder conn = 
        new EntityConnectionStringBuilder(DBEntities.dbConnection);
    SqlConnection s = new SqlConnection(conn.ProviderConnectionString);
    
    0 讨论(0)
  • 2021-01-31 03:27

    In my case I just needed to execute an update statement so I used the following construct

    _db.Database.ExecuteSqlCommand($"update ChiusureTurni set esportato = 1 where idChiusuraTurni = {idChiusura}");
    

    where _db is my db context in this case I took advatage of transaction management

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