Matheus, I believe you are not taking into account one thing: LazyLoad
.
Defined to LazyLoad, when searching for a Student
, only Student
data is retrieved from the Bank, only if you come to access the Standard
Browsing property that EF will fetch your data. / p>
To do this lazy loading, it is necessary that the navigation property has the virtual
modifier, so EF can modify its behavior.
Note the mapping of your entities using Code First
, you might notice this better.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
public partial class Contexto : DbContext
{
public Contexto() : base("name=Contexto")
{
}
public virtual DbSet<Standard> Standards { get; set; }
public virtual DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Standard>().Property(e => e.Name).IsUnicode(false);
modelBuilder.Entity<Standard>().HasMany(e => e.Students).WithRequired(e => e.Standard).WillCascadeOnDelete(false);
modelBuilder.Entity<Student>().Property(e => e.Name).IsUnicode(false);
}
}
[Table("Student")]
public partial class Student
{
public int StudentID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public int StandardID { get; set; }
public virtual Standard Standard { get; set; }
}
[Table("Standard")]
public partial class Standard
{
public Standard()
{
Students = new HashSet<Student>();
}
public int StandardID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
If you create a new Student
entity, and set a value to StandardID
that already exists in the database, and after trying to access the Standard
property, EF fetches the data from the% in the Database.
But if you do not access the navigation property and only set the Standard
property value, the additional query will not be performed, but if you try to save the StandardID
entity, EF will have no problem doing so.
Note that it is not always necessary to access a navigation property, sometimes knowing only the ID of the property is enough.