admin管理员组文章数量:1289384
When having to forego EF Core and do some ADO operations against the database, how do you safely use the EF Core managed connection? For example, I need to execute a reader. Currently this is what I do:
var cmd = DataContext.Database.GetDbConnection().CreateCommand();
cmd.CommandText = sqlToUse;
cmd.CommandType = CommandType.Text;
using (cmd)
{
if (cmd.Connection.State == ConnectionState.Closed)
cmd.Connection.Open();
if (DataContext.Database.CurrentTransaction != null)
cmd.Transaction = DataContext.Database.CurrentTransaction.GetDbTransaction();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// Do the things
}
}
}
Is there anything that I need to do with the connection afterwards whether or not I've opened the connection?
When having to forego EF Core and do some ADO operations against the database, how do you safely use the EF Core managed connection? For example, I need to execute a reader. Currently this is what I do:
var cmd = DataContext.Database.GetDbConnection().CreateCommand();
cmd.CommandText = sqlToUse;
cmd.CommandType = CommandType.Text;
using (cmd)
{
if (cmd.Connection.State == ConnectionState.Closed)
cmd.Connection.Open();
if (DataContext.Database.CurrentTransaction != null)
cmd.Transaction = DataContext.Database.CurrentTransaction.GetDbTransaction();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// Do the things
}
}
}
Is there anything that I need to do with the connection afterwards whether or not I've opened the connection?
Share Improve this question edited Feb 19 at 19:06 Thom A 96k11 gold badges60 silver badges92 bronze badges asked Feb 19 at 18:47 Jason ButeraJason Butera 2,4603 gold badges31 silver badges48 bronze badges 1- Related: github/dotnet/efcore/issues/7810 (a tad too long for me to read all and summarize) – Peter B Commented Feb 19 at 18:55
2 Answers
Reset to default 0If EF is responsible for providing your connection, EF will dispose of it after use. If you close or dispose the connection, your DataContext will most likely not work as you expect.
I don't think it's necessary to check for ConnectionState == Open, I probably wouldn't unless I see problems related to it
check this link
Assuming you didn't pass an existing connection to the DbContext constructor, if you Open a connection it will remain open for the life of the DbContext and be closed with the DbContext is Disposed.
You may Close the connection in your method, and EF will re-open it as necessary, or just leave it open. Just don't Dispose() the connection.
版权声明:本文标题:sql server - Execute a reader while still playing nice with the currently managed connection - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741476914a2380939.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论