While working in a project I saw a strange behaviour I cannot understand with the loading of navigation properties.
Here is a small example that reproduces this "problem".
I want to load a Year, without including data of the company(navigation property).
My code:
public static Year GetYear(int id)
{
using (var context = new testModelContainer())
{
var result = context.YearSet.FirstOrDefault(c => c.Id == id);
//Company test = context.CompanySet.Where(c => c.Id == id).FirstOrDefault();
return result;
}
}
This returns the year I want, without data in the navigation property, but if I uncomment the line and I just execute the line, maybe because I want to know the name of the company or whatever, it authomatically includes the company data into the Company navigation property of the Year.
Any idea how to prevent this behaviour? For security reasons I would want to avoid sendind data of the 'parents'.
I am using EF 6, .NET 4.5.
This is because you are executing your commands in one context. Entities share information about each other if working within one context.
Thus if you first retrieved the Year
and then you retrieve the Company
that has a reference to Year entity with the value of previously retrieved Year, your navigation property will be updated automatically and vice versa - Year will have Company property populated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With