Matheus, I believe you’re not taking one thing into account: LazyLoad
.
Defido to Lazyload, to fetch one Student
, only the data of Student
are recovered from the Bank, only if you come to access the Navigation property Standard
that the EF will fetch your data.
To make this load lazy, it is necessary that the navigation property has the modifier virtual
, with this the EF can modify the behavior of the same.
Observe the mapping of your entities using Code First
, maybe you can notice it 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 entity Student
, and set a value for StandardID
that already exists in the database, and after this try to access the property Standard
the RU retrieves the data from the Entity Standard
in the Database.
But if you do not access the navigation property and only set the Property Value StandardID
, the additional query will not be performed, but if you try to save the entity Student
, EF will have no problem doing it.
Note that it is not always necessary to access a navigation property, sometimes knowing only the ID of the same is enough.
It is not clear what
[ForeignKey]
has to do with the question. If you think you have redundancy, you need to look at the context. It may be redundant, but it was a decision of who made this code. But it may not be. It is without context.– Maniero