Entity Framework Extra column when using ICollection

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

public class tabela1{

   public Guid tabela1Id {get;set;}

  //campos...

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

}
The Entity Framework will create an index (an extra column in the tabela2 ) of the tabela1 in the tabela2 , with the primary key of the tabela1 with the name of: tabela1_tabela1Id

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

    
asked by anonymous 02.09.2015 / 16:03

1 answer

3

I do not much agree with this nomenclature of tabela because the Entity Framework is database agnostic, so it does not necessarily operate on the relational model, just over 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 the 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:

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 }
}
    
02.09.2015 / 16:16