简体   繁体   中英

EFCore Lazy Loading with multiple where statements

I have configured DbContext with lazy loading using proxies:

services.AddDbContext<MyDbContext>(options =>
                options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("Connection"), sqlServerOptions => sqlServerOptions.CommandTimeout(90)), ServiceLifetime.Transient);

I use IQueryable to define a query against an entity that have multiple navigation properties:

IQueryable<Entity> query = context.Entity;

After that, I have defined a filter in a where clause using multiple Func:

 Func<Entity, int, bool> GetByParentId = (entity, id) => { return entity.ParentId == id; };
 Func<Entity, string, bool> FilterByName = (entity, textToSearch) => { return entity.Name.Equals(textToSearch, StringComparison.OrdinalIgnoreCase); };
 Func<Entity, string, bool> FilterByStatus = (entity, textToSearch) => { return entity.IdStatusNavigation.Description.ToLower().Contains(textToSearch); };

 Func<AssetGroup, int, string, bool> FilterEntities = (entity, idParam, textToSearch) => {
                return GetByParentId (entity, idParam)
                    && (FilterByName(entity, textToSearch) || FilterByStatus(entity, textToSearch));
            };

query = query.Where(entity=> FilterEntities(entity, idParam, lowerTextToSearch));

When I do a for(var entity on query) the first function with navigation property is executed ( FilterByName ) and all properties on the entity, including navigation properties, have values and I can navigate to the related entities.

But when the second function is executed ( FilterByStatus ) I'm getting the following error:

An attempt was made to lazy-load navigation property 'IdStatusNavigation' on detached entity of type 'EntityProxy'. Lazy-loading is not supported for detached entities or entities that are loaded with 'AsNoTracking()'

I have not used AsNoTracking... If I debug the process I can see that on the second function navigation properties throw exception System.InvalidOperation.

How can I solve this error?

Thanks a lot, Regards

Seems that Functions types cannot be translated to SQL Language, so this piece of code are executed when the query result is in memory. So after the first navigation property is accessed all navigation properties seems to be dispose and cannot be accessed on a future.

So I have rewritte the code in order to make this filters with data on memory (after a ToList() execution).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM