Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework loads navigation properties without asking for them

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".

enter image description here

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.

like image 944
blfuentes Avatar asked Apr 28 '14 12:04

blfuentes


Video Answer


1 Answers

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.

like image 76
Andrew Avatar answered Oct 12 '22 00:10

Andrew