EntityFramework.Docs icon indicating copy to clipboard operation
EntityFramework.Docs copied to clipboard

Document other "raw" database access APIs besides FromSql

Open divega opened this issue 7 years ago • 4 comments

We should add more information about ExecuteSqlCommand and GetDbConnection, including how to manage the open/close state (e.g. with context.Database.OpenConnection and context.Database.CloseConnection vs. connection.Open and connection.Close) and lifetime of the connection returned with the latter (see https://github.com/aspnet/EntityFrameworkCore/issues/11415).

divega avatar Mar 26 '18 21:03 divega

@divega can you briefly describe here should user close connections obtained by GetDbConnection, or it would be auto-closed with Context?

Mart-Bogdan avatar Sep 08 '18 14:09 Mart-Bogdan

@Mart-Bogdan For DbConnections in general with EF Core:

  • You should dispose it if and only if you created it
  • If you explicitly open the connection, then you should explicitly pair that open with a close.

GetDbConnection gives access to the underlying DbConnection that EF is using, so you shouldn't dispose it unless you originally created the connection and passed it to EF in the first place. With regard to closing, it's best practice if you open it to then close it.

ajcvickers avatar Sep 10 '18 15:09 ajcvickers

See also #1787

ajcvickers avatar Jan 15 '20 22:01 ajcvickers

Splitting #1787 out again, since this issue seems to be (also) about DbConnection lifecycle/ownership issues which aren't unique to ExecuteSql (e.g. also ExecuteUpdate, even querying?). Let's discuss...

roji avatar Sep 19 '22 15:09 roji