Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove underscore in foreign key names generated by Entity Framework 4.1

I have a relationship using Entity Framework 4.1 and my foreign key's is generated automatically, the names of foreign key have underscore:

public class Setor : Entity
{
    public long Id { get; set; }
    public string Nome { get; set; }
    public virtual Secretaria Secretaria { get; set; }
}

public class Secretaria : Entity
{
    public long Id { get; set; }
    public string Nome { get; set; }
}

This generated foreign key named: Secretaria_Id in table Setor

I want to remove this underscore: SecretariaId

Is there a way to do this? I prefer using DataAnnotations.

like image 243
Acaz Souza Avatar asked Jul 19 '11 14:07

Acaz Souza


1 Answers

In Fluent API you can give the FK columns a name:

modelBuilder.Entity<Setor>()
    .HasOptional(s => s.Secretaria)
    .WithMany()
    .Map(a => a.MapKey("SecretariaId"));

I think this is not possible with DataAnnotations. Alternatively you can expose the foreign key into your model class, like so:

public class Setor : Entity
{
    public long Id { get; set; }
    public string Nome { get; set; }
    public long? SecretariaId { get; set; }
    public virtual Secretaria Secretaria { get; set; }
}

Conventions will recognize this automatically as the FK and the column name will be the name of the property, i.e. SecretariaId.

like image 62
Slauma Avatar answered Oct 15 '22 04:10

Slauma