How to set manually an Oracle Connection String in a DbContext

后端 未结 3 2050
南旧
南旧 2021-02-15 23:51

I have the following connection string:



        
相关标签:
3条回答
  • 2021-02-16 00:30

    To create a DbContext using Oracle without use WebConfig, your inheritance of DbContext must inject an Oracle Connection to base constructor:

    class MyDbContext: DbContext
    {
        public MyDbContext() : base(new OracleConnection("DATA SOURCE=Server; PASSWORD=123;USER ID=SYSTEM"){}
        ...
    }
    
    0 讨论(0)
  • 2021-02-16 00:33

    Just found the solution after struggling with this all afternoon. Seems that the constructor or DbContext will use either the connection string or connection string name, which is not the same, if you pass a connection string it will default to SqlClient which is the only thing bundled by default in .NET

    Now, if you, instead of using the whole connection string, pass just the connection string name then it will internally parse also the "providerName" parameter which has the assembly name for the DB provider Oracle.DataAccess.Client for instance.

    So instead of passing the connection string to the DbContext constructor just pass the connection string name, like this:

    .config file:

    <connectionStrings>
        <add name="SQLServer" connectionString="Server=localhost; Database=MyDb; User ID=MyUser;Password=MyPwd;Pooling=false" providerName="System.Data.SqlClient" />
        <add name="Oracle" connectionString="Data Source=localhost:1521/XE;Persist Security Info=True;User ID=MyUser;Password=MyPwd;" providerName="Oracle.ManagedDataAccess.Client"/>
    </connectionStrings>
    <appSettings>
        <add key="DefaultConnection" value="Oracle" />
    </appSettings>
    

    And in your DbContext:

    public MyDbContext()
        : base("DefaultConnection")
    {
    
    }
    

    That way you just set up a config key with the name of the connection string you want to hook the context to and use it in the constructor. If you do it this way EF will automatically parse the whole connection string tag and not only the connectionString attribute value, hence, load the right provider.

    Do note that I'm using Oracle.ManagedDataAccess.Client which is newer and only included in ODAC / ODP.NET v12 and above. If you use ODAC 11 you should use Oracle.DataAccess.Client in providerName instead.

    0 讨论(0)
  • 2021-02-16 00:36

    Got it working by specifying "Default Connection Factory" in web/app .config

    <configuration>
    ...
        <entityFramework>
            <defaultConnectionFactory type="Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory, Oracle.ManagedDataAccess.EntityFramework" />
            <providers>
              ...
    

    https://docs.oracle.com/cd/E63277_01/win.121/e63268/entityCodeFirst.htm

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