首页 > 解决方案 > 使用 Lazyloading,如何在使用新的 DbContext 处理完其 DBContext 后加载相关对象?

问题描述

我有一个通用方法,用于从数据库中提取实体。

在这个通用方法中,我使用 IDbContextFactory 来获取我可以查询的 DbContext 对象。

    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;
            }
        }
    }

这适用于不相关但我收到问题/警告的对象

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.

当我尝试访问引用相关数据的模型中的数据时。

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

假设我发现了这个错误,我将如何将一个新的 DbContext 链接到这个 Lazy Loader 以便我可以获取数据?

有没有办法检查一个属性以提前知道我需要在尝试访问该值之前生成/链接一个新的 DbContext 吗?

标签: c#entity-frameworkgenericsdbcontext

解决方案


我将如何将新的 DbContext 链接到这个 Lazy Loader 以便我可以获取数据?

你不能。延迟加载代理绑定到单个 DbContext 实例。using如果您想使用延迟加载,您应该为 DbContext 找到比块更好的生命周期。

如果需要,您还可以将实体附加到稍后的 DbContext 并显式加载相关实体。


推荐阅读