Entity Framework Extra column when using Icollection

Asked

Viewed 97 times

2

If I have two tables in the bank, for example: tabela1 and tabela2, and in the tabela1 I have a ICollection of tabela2:

public class tabela1{

   public Guid tabela1Id {get;set;}

  //campos...

  public ICollection <tabela2> tabela2 {get;set;}

}

Entity Framework will create an index (one more column in the tabela2) of tabela1 in tabela2, with the primary key of the tabela1 by the name of: tabela1_tabela1Id

How can I prevent him from creating that column too much? Or how can I change the name he gives to that column?

1 answer

3


I don’t agree with that nomenclature of tabela even because the Entity Framework is agnostic about the database, so it doesn’t necessarily operate in the relational model, just on top of tables. It goes beyond that. But back to the answer:

Having this statement:

public class tabela1 
{

   public Guid tabela1Id {get;set;}

  //campos...

  public ICollection <tabela2> tabela2 {get;set;}
}

You need to have this:

public class tabela2
{
    [Key]
    public Guid tabela2id { get; set; }
    // Anote também a FK, assim:
    public Guid tabela1id { get; set; }

    public virtual tabela1 tabela1 { get; set }
}

This generates FK with the name tabela1id.

Now, if you want another name for FK, use the [ForeignKey] as follows:

public class tabela2
{
    [Key]
    public Guid tabela2id { get; set; }
    // Anote também a FK, assim:
    public Guid MinhaFKCujoNomeEuEscolhi { get; set; }

    [ForeignKey("MinhaFKCujoNomeEuEscolhi")]
    public virtual tabela1 tabela1 { get; set }
}

Or else:

public class tabela2
{
    [Key]
    public Guid tabela2id { get; set; }
    // Anote também a FK, assim:
    [ForeignKey("MinhaPropriedadeDeNavegacaoCujoNomeEuEscolhi")]
    public Guid tabela1id { get; set; }

    public virtual tabela1 MinhaPropriedadeDeNavegacaoCujoNomeEuEscolhi { get; set }
}
  • This nomenclature used only as an example here, and this is possible to be done using Fluent API ?

  • Possible, but I find the Fluent API more complicated to use.

Browser other questions tagged

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