Entity Framework: DbContext and setting the ProviderName

前端 未结 3 1577
难免孤独
难免孤独 2020-12-10 10:53

When you derive from DbContext and use the parameter-less constructor it will load a connection string from web.config. You also have the option of explicitly specifying the

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 11:20

    Create your DbConnection manually and pass it to the DbContext constructor as follows:

    var conn = DbProviderFactories.GetFactory("MY_CONN_PROVIDER").CreateConnection();
    conn.ConnectionString = "MY_CONN_STR";
    
    new DbContext(conn, true);
    

    Notice the second parameter bool contextOwnsConnection is true. Since you don't re-use the connection elsewhere, it lets the context manage the connection and Dispose() it when needed.

提交回复
热议问题