Mandelbrotter
Mandelbrotter

Reputation: 2436

Using Lazyloading, how to load a related object after disposal of its DBContext by using a new DbContext?

I have a generic method that I use to extract entities from a database.

In this generic method I use IDbContextFactory to get a DbContext object that I can query.

    public virtual List<T> GetTableRecordsByPartialInstance<T>(T whereObject) where T : class, ITable
    { 
        using (SqlDboDbContext cntx = _DboContextFactory.CreateDbContext())
        {
            string tableName = cntx.Model.FindEntityType(typeof(T)).GetTableName();                
            string query;
            List<SqlParameter> parameters;
            GetQuery_NotNullWhereJoinWithAnd(whereObject, tableName, out query, out parameters);
            IQueryable<T> queryObj = null;
            try
            {
                queryObj = cntx.Set<T>().FromSqlRaw(query, parameters.ToArray());
                
                return queryObj.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                string strQuery = "";
                strQuery = queryObj.ToQueryString();
                throw;
            }
        }
    }

This works well for objects that aren't related but I'm getting the issue/warning

System.Reflection.TargetInvocationException

Inner Exception 1:
InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.LazyLoadOnDisposedContextWarning': An attempt was made to lazy-load navigation 'PartyProfile.PartyProxy' after the associated DbContext was disposed.

when I try to access data in my model referencing related data.

return typeof(TT).GetProperties().All(x => SomeMethod(x.GetValue(val)));

Assuming I catch this error how would I go about linking a new DbContext to this Lazy Loader so that I could get the data?

Is there a way to check a property to know ahead of time that I would need to generate/link a new DbContext before trying to access the value?

Upvotes: 0

Views: 468

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89406

how would I go about linking a new DbContext to this Lazy Loader so that I could get the data?

You can't. Lazy Loading proxies are tied to a single DbContext instance. You should find a better lifetime for your DbContext than a using block if you want to use Lazy Loading.

You can also attach an entity to a later DbContext and explicitly load related entities if you want.

Upvotes: 1

Related Questions