简体   繁体   中英

related entities included only intermittently in Entity Framework query

I have an entity framework query where items are displayed based on a variable set of user-defined criteria. The final query is supposed to include the related entity "Subjects", but only does so in an intermittent fashion. That is, in the same result set, some results will include their subjects while others will not. To make matters even more bizarre, the same record "a" will include its related subjects in one request, but not in another, even though I am using the same select code in both cases. Here's the relevant snippet of the final select:

 var newQuery = query.Select(l => new
            {
                RecordId = l.RecordId,
                RawFileId = l.RawFileId,
                Subjects = l.RecordSubjects.Where(s => s.Subject.ClientId == data.ClientId && l.RecordId == s.RecordId && s.IsActive).Select(s => new { Name = s.Subject.Name, SubjectId = s.Subject.SubjectId, Description = s.Subject.Description }),

                Url = (l.Url == null) ? "#" : l.Url, //make sure all results display a valid Url, even if the field is null
                RegionCode = l.RegionCode ?? "",
                RegionName = l.Region.Name ?? "",
                Year = l.Year

            }

I've eliminated a bunch of additional fields and other related entities for clarity.

UPDATE: To further clarify, I can run the same exact query and have the subjects appear for a specific record the first time, and have nothing show up the next. So it can't be anything about the data, I don't think.

Try throwing a .AsEnumerable(). before the Select , ie, query.AsEnumerable().Select( This would force retrieval of all the required data rather than leaving it subject to lazy loading. Ie, perhaps some of the Subject entities may have been loaded by EF and are present, while others are not present but will be lazy loaded on demand, which may be why you are getting this intermittent behavior. Doing a .AsEnumerable() forces loading of all the results for the Subject Entities from the database. Of course, this may incur a performance overhead that is not acceptable for your use case.

Update

Also wondering if data.ClientId could be part of the problem. data is not in the sample you posted.

Update 2 As @TravisJ implies in comments below, it is unlikely that my answer is correct or fully correct for @acullen72's situation. However, @acullen72 is asking that the post stay up for now.

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