'Calling Database.GetDbConnection() twice in a row causes a System.NullReferenceException
public async Task<IEnumerable<Bar>> GetFoo()
{
using var connection = this.Database.GetDbConnection();
var bars = new List<Bar>();
try{
var cmd = new SqlCommand
{
CommandText = "select * from GetFoo()",
CommandType = System.Data.CommandType.Text,
Connection = connection as SqlConnection
};
await connection.OpenAsync();
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
var bar = new Bar
{
Foo = (string) reader["FOO"],
};
bars.Add(bar);
}
}
finally
{
//await connection.CloseAsync();
//await connection.DisposeAsync();
}
return bars;
}
When running this method twice I get:
System.NullReferenceException: 'Object reference not set to an instance of an object.' at line await connection.OpenAsync();
This is what I know:
If EF creates the DbConnection object, then EF will ensure it is disposed when the DbContext is disposed. On the other hand, if some other code creates the DbConnection object and passes it to EF, then it is the responsibility of the other code to also dispose the connection appropriately.
So what am I doing wrong here? Is there any way to overcome this issue? Can this.Datbase.GetDbConnection() be called twice in the same instance?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
