9

I am using EntityFramework for the first time and maybe this question is so simple...I've used code first method..I have a Class Personnel which looks like this:

public class Personnel { public string Id { set; get; } public int Code { set; get; } public string Name { set; get; } public int Type { set; get; } public JobTitle Title { set; get; } } 

and the JobTitle class:

public class JobTitle { public string Id { set; get; } public int Number { set; get; } public string Title { set; get; } public List<Personnel> Personnels { set; get; } } 

which the last property in Personnel Class is a foreign key in personnel table of course..my problem is when I want to retrieve all personnels ( or a personnel ) from DB using lambda expression..the foreign key object is null..the lambda expression is like below:

Context.ContextInstance.Personnels.ToList(); 

and if I change the expression to this the foreign key object is not null any more.

 Context.ContextInstance.Personnels.Include("Title").ToList(); 

is it the right way??..is there any better way??..I supposed that EF will automatically understand that!!!!..if there are more than 1 FK then I have to use Include for all of them?? please help me to understand.

Thanks

1

2 Answers 2

7

This is due to lazy loading. When you call Context.ContextInstance.Personnels.ToList(); this will fetch all personnel's but Title will not fetch until it get instanced, so make it virtual to get it.

or, you can disable lazy loading by

public MyEntitiesContext() : base("name=MyEntitiesContext", "MyEntitiesContext") { this.Configuration.LazyLoadingEnabled = false; } 

Doing this will get all related data from context. Using "include" is loading on demand, when you specify properties you want to query.

Virtual keyword allows entity framework runtime create dynamic proxies for your entity classes and their properties, and by that support lazy loading. Without virtual, lazy loading will not be supported, and you get null on collection properties.

Sign up to request clarification or add additional context in comments.

Comments

6

If your JobTitle property would be defined as virtual, you wouldn't need to use include.

It's really good explained here: Entity Framework 4.1 Virtual Properties

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.