EntityFramework Query Returns the same object for relationship

痴心易碎 提交于 2020-01-06 18:35:47

问题


I'm having trouble phrasing the title into something that makes more sense, so I'm going to be a little verbose in my question.

I have this EF query:

    var allSocs = _db.Socs
    .Where(x => x.Soc6 != null)
    .Select(x => new SocModel {
        OccupationalEmploymentStatistics = x.OccupationalEmploymentStatistics
                    .Where(y => y.GeographyId == 25 && y.Release == "2015A01" && y.Naics == "000000")
                    .OrderByDescending(z => z.AnnualWageMedian),
        Soc6 = x.Soc6,
        OnetSocs = x.OnetSoc,
        Name = x.Name,
        Description = x.Description,
        EmploymentProjections = x.EmploymentProjections
                    .Where(y => y.GeographyId == "201400" && y.Naics == "000000")
    }).ToList();  

It's returning a list of Objects called Socs, who have some primitive properties and three Object properties, Onetsocs, OccupationalEmploymentStatistics, and EmploymentProjections.

The behavior I'm having is that all of the non-object fields are working fine, as are EmploymentProjections and OnetSocs.

The issue is that OccupationalEmploymentStatistics is acting weird. It seems to be that EF is only getting one OccupationalEmploymentStastic and applying it to all records in _db.Socs.

If I set a breakpoint and mouse over _db.Socs, I'm shown that there is only one object. However, allSocs has the proper number of Socs in it (841).

I've tried removing the OrderByDescending to see if maybe that was the issue, but I'm still getting the same behavior.

For some background info, the tables that I'm working with are all external tables, and I had to draw the relationships manually since EF didn't pick up on them.

EDIT: Some more background info. If I make another query that's just var socs = _db.Socs.ToList(), only the first record has any OccupationalEmploymentStatistics at all. None of the other records have any


回答1:


Because EF uses the Identity Map pattern. Basically, an EF session will only store one instance for a given entity and id, and it will always reuse the same instance, whenever some entity points to the same DB table and primary key.



来源:https://stackoverflow.com/questions/42249043/entityframework-query-returns-the-same-object-for-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!