0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bryan
  • 3,421
  • 8
  • 37
  • 77
  • How long does it take in minutes to get that exception? Does it take up to 5 minutes? – Peter Bons Sep 02 '22 at 14:01
  • @PeterBons longer than 5minutes – Bryan Sep 02 '22 at 14:02
  • Are you running on a consumption plan? My guess is that the maximum [running time](https://learn.microsoft.com/en-us/azure/azure-functions/functions-host-json#functiontimeout) has been exceeded, the function runtime shutsdown the function and than this error occurs – Peter Bons Sep 02 '22 at 14:04
  • @PeterBons Im running it locally on my computer. So not in Azure. – Bryan Sep 02 '22 at 14:05
  • Hmm are there any other logs indicating a failure or a shutdown? – Peter Bons Sep 02 '22 at 14:08
  • @PeterBons no, not what I can see.. It's like the function disposes my objects after some time... – Bryan Sep 02 '22 at 14:32
  • You could try setting the function timeout way shorter: https://stackoverflow.com/a/47447550 and then see if you get the same error. I assume the local Host implementation also honors that setting. You don't happen to have a full stack trace? – rene Sep 02 '22 at 14:42
  • 1
    If you get an EF Core `dbContext` already - **why** are you using a low-level `SqlConnection` and probably Dapper to load your data? Why aren't you using the system-provided EF Core `dbContext` instead? – marc_s Sep 02 '22 at 16:01
  • @marc_s does that have anything to do with my issue that I have? – Bryan Sep 03 '22 at 08:15
  • You can register the DbContext as PooledDbContext, and inject IDbContextFactoryin your class. At the beginning of Function1, the factory can returns a not busy instance of DbContext. – Alireza Memarian Mar 31 '23 at 15:03

0 Answers0