I have the following code in my Azure function:
public class Function1
{
private readonly DatabaseContext _dbContext;
public Function1(DatabaseContext dbContext)
{
_dbContext = dbContext;
}
[FunctionName("Function1")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string locationConnectionstring = "connectionstring";
using (var connection = new SqlConnection(locationConnectionstring))
{
try
{
var itemRelpInst = await connection.QueryAsync<ItemsRelProductInstances>("Select ProductInstanceId, ItemId FROM ItemsRelProductInstances"); // Returns 200k of data
var results = itemRelpInst.GroupBy(
p => p.ProductInstanceId,
p => p.ItemId,
(key, g) => new { ProductInstanceId = key, Items = g.ToList() });
foreach (var rel in results)
{
var pEntity = await _dbContext.ProductInstances.FirstOrDefaultAsync(x => x.ProductInstanceId == rel.ProductInstanceId);
if (pEntity != null)
{
List<Item> items = new List<Item>();
var distinctItems = rel.Items.Distinct();
foreach (var item in distinctItems)
{
var itemEntity = await _dbContext.Items.FirstOrDefaultAsync(x => x.Id == item);
items.Add(itemEntity);
}
pEntity.Items = items;
await _dbContext.SaveChangesAsync();
}
}
}
catch (Exception ex)
{
throw;
}
}
}
}
Here is my Startup
class:
var localConnectionString = @"Server=(localdb)\mssqllocaldb;Database=EFPoc;Integrated Security=True;";
builder.Services.AddDbContext<DatabaseContext>(
options => options.UseSqlServer(localConnectionString));
What I'm trying to do is to migrate data from a table in one database, into my local database that are using Entity Framework Core.
When I run my application, it starts inserting data. But after some time, around when it has inserted 16k of data, I get the following exception:
Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'DatabaseContext'.
I have no idea what causes this exception. Any suggestions?