Questions with navigation and FK properties with Code First

Asked

Viewed 60 times

0

Why in this code was identified as foreign key the Idgroup property and not the navigation property and what would be the correct form of the foreign key application?

public class Grupo
{
    public Grupo()
    {
        Produtoes = new List<Produto>();
    }

    public int GrupoId { get; set; }
    public string Nome { get; set; }
    public virtual ICollection<Produto> Produtoes { get; set; }
}

public class Produto
{
    public int ProdutoId { get; set; }
    public string Nome { get; set; }
    public int IdGrupo { get; set; }
    public decimal? Custo { get; set; }
    public decimal? Venda { get; set; }
    public decimal? Saldo { get; set; }
    public decimal? Promocao { get; set; }
    public virtual Grupo Grupo { get; set; }
}

public partial class DBContexto : DbContext
{
    static DBContexto()
    {
        Database.SetInitializer<DBContexto>(null);
    }

    public DBContexto()
        : base("DBContexto")
    {
    }

    public DbSet<Grupo> Grupoes { get; set; }
    public DbSet<Produto> Produtoes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    }
}
  • 1

    You came to generate a Migration this code to check whether IdGrupo was even mapped as foreign key?

  • Gypsy, I have not yet used Migration in this code, I just ran the code to generate the entities in the database, however, I found that the names of both the navigation property and FK do not match. My doubt arose from that, if I have a navigation property, why did that code pick up Idgrupo as FK?

  • 1

    If you took it, for me it’s something new. Possibly the naming conventions allow you to use IdGrupo and GrupoId.

  • Regarding generating as a foreign key yes, the Idgroup was generated as a FK, but what was the sense then of the Group navigation property?

  • 1

    There are several. For example, if you want to write in a View the name of the Group having the Product, can make produto.Grupo.Nome. If you want to assign a new Product Group, you can produto.Grupo = db.Grupos.Single(/* Uma condição qualquer */). The huge advantage of the navigation property is that the Entity Framework takes care of it for you.

  • Then the EF automatically identifies as a FK the properties that have in the ID name, even if I do not inform the Data Annotation [Foreignkey] and independent of whether or not I create a FK, just because I have a navigation property, the EF will generate a FK for me?

  • 1

    Exactly. It needs to relate the two entities somehow, so it checks several things, from the navigation properties to the Fluent API.

  • Thank you Gypsy!

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.