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)
{
}
}
You came to generate a Migration this code to check whether
IdGrupo
was even mapped as foreign key?– Leonel Sanches da Silva
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?
– Kelly Soares
If you took it, for me it’s something new. Possibly the naming conventions allow you to use
IdGrupo
andGrupoId
.– Leonel Sanches da Silva
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?
– Kelly Soares
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 canproduto.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.– Leonel Sanches da Silva
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?
– Kelly Soares
Exactly. It needs to relate the two entities somehow, so it checks several things, from the navigation properties to the Fluent API.
– Leonel Sanches da Silva
Thank you Gypsy!
– Kelly Soares