I have a poco class which is wired up to the entity framework. The class is called PersonalizationCatalogPrice. This class has a sub object called Pricelevel which does not have the virtual keyword on it. Because of this (based on my understanding) this object should never lazy load and should return null. However, we have found that this object seems to load up when used in a specific manner.
so the basic class structure is this
public class PersonalizationCatalogPrice
{
public int PersonalizationCatalogPriceID { get; set; }
public int PersonalizationCatalogId { get; set; }
public virtual PersonalizationCatalog PersonalizationCatalog { get; set; }
public decimal CustomerRetail { get; set; }
public decimal ConsultantCost { get; set; }
public decimal PersonalVolume { get; set; }
public decimal QualifyingVolume { get; set; }
public int PriceLevelId { get; set; }
public PriceLevel PriceLevel { get; set; }
}
Here is an example. In the first line we return an Iqueryable of PersonalizationCatalogPrice items. In the second line we have another IQueryable and we are using the priclevel object in this iQueryable (see the line "contains pcp.pricelevel"). When we do this, the pricelevel object loads up even though it has no virtual keyword.
IQueryable<PersonalizationCatalogPrice> allPersPriceRecords = _e2ReposMan.PersonalizationRepository.GetSomeRecords();
//List<PersonalizationCatalogPrice> persprices = allPersPriceRecords.ToList();
var persQuery = from pl in personalizationLines
join pcp in allPersPriceRecords on pl.Item2.PersonalizationCatalogPriceID equals pcp.PersonalizationCatalogPriceID
where !HostessPriceLevelTypes().Contains(pcp.PriceLevel.PriceLevelTypeId)
select pl.Item2.PersonalVolume * pl.Item1;
var openOrdersTotal = (query.Any() ? query.Sum() : 0) + (persQuery.Any() ? persQuery.Sum() : 0);
Modifying this code by uncommenting the second line which performs a ToList() however. Makes the pricelevel subobject return null as expectedd since it does not have a virtual keyword on it and the entity framework then works as we anticipate. (EF 6)
Does anyone know why we are able to load the pricelevel property when we do not do the toList().
thanks for any assistance.
allPersPriceRecords
is anIQueryable<>
which, unless "executed" (by, e.g. enumeration), will be treated as LINQ to Entities query, and will be "translated" into a (SQL) query - i.e. accessing particular navigation properties will result in extra joins in the query. But once you "execute" it (by callingToList()
) it's results will be cached, and from that point it no longer will be "executed", i.e. whenever you access it's results you'll be in fact using LINQ to Objects, and not LINQ to Entities. But, as I mentioned, its just my guess. – Grx70