Navigation properties that do not load properly

My context looks like this:

public class ApplicationDbContext: IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection") { this.Configuration.LazyLoadingEnabled = true; } //DbSet properties } 

therefore, lazy loading is enabled.

I have the following class:

 public class Home { private ICollection<Slide> _slides; [Key] [Required] public string Name { get; set; } [ForeignKey("Header")] public int? HeaderID { get; set; } //Navigation properties public ICollection<Slide> Slides { get { return _slides ?? (_slides = new List<Slide>()); } set { _slides = value; } } public Content Header { get; set; } } 

Note that both the Header and Slides navigation properties are used without the virtual . As far as I know , when we do not use the virtual - properties should be loaded with impatience.

However, when I get my Home object from the database, both of my navigation properties are null (but the HeaderID property matters).
Even if I switch to this.Configuration.LazyLoadingEnabled = false; - preloaded parameters - they are still null .

This is how I get my data from db (using the repository template):

 public static Home GetHomeComponent( this IRepositoryAsync<Home> repository) { var result = repository .Query() .Select() .First(); return result; } 

I solved the problem with Include properties:

 public static Home GetHomeComponent( this IRepositoryAsync<Home> repository) { var result = repository .Query() .Include(x => x.Header) .Include(x=>x.Slides) .Select() .First(); return result; } 

However, this is not convenient for me (since I have too many navigation properties to load).

So my question is:
I do not use the virtual , but why are my navigation properties not loading impatiently?
Or am I doing something wrong? Is there any other way to load my navigation properties without using Include ?

+7
c # asp.net-mvc entity-framework entity-framework-6
source share
1 answer

If you do not use the virtual , this means that after trying to access a non-virtual property, it will not be loaded from the database, but you will get Null .

This does not mean that you will have all the properties of the objects populated at once, in order to fill in Slides for EG in your code, you should use .Include () - this is an active load to load the property yourself before it is used.

You can create a universal function that will fill in the required properties using the arguments it receives (using parameters) to get more detailed information:

EntityFramework Eager Load All Navigation Properties

+8
source share

All Articles