Leonardo
Leonardo

Reputation: 11391

Change EF6 key FK convention

EF by default name my FKs as EntityName_id and I would like it to be named id_EntityName. How can I do that?

Edit1:
There are over 700 FKs here... automate this would be a lot faster I belive... Also intend to use the same answer to normalize composite PKs...

Upvotes: 0

Views: 82

Answers (3)

Peter
Peter

Reputation: 12711

MSDN has an example of creating a custom ForeignKeyNamingConvention. You could modify this example to name the Foreign Keys according to your convention.

I haven't tested this, but here's some rough code that you might be able to build on:

public class ForeignKeyNamingConvention : IStoreModelConvention<AssociationType>
{
    public void Apply(AssociationType association, DbModel model)
    {
        if (association.IsForeignKey)
        {
            var constraint = association.Constraint;

            for (int i = 0; i < constraint.ToProperties.Count; ++i)
            {
                int underscoreIndex = constraint.ToProperties[i].Name.IndexOf('_');
                if (underscoreIndex > 0)
                {
                    // change from EntityName_Id to id_EntityName
                    constraint.ToProperties[i].Name = "id_" + constraint.ToProperties[i].Name.Remove(underscoreIndex);
                } 
            }
        }
    }
}

You can then register your custom convention in your DbContext's OnModelCreating() method like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)  
{  
    modelBuilder.Conventions.Add<ForeignKeyNamingConvention>();  
} 

Upvotes: 2

JarekCz
JarekCz

Reputation: 21

I think that the best way is to use fluent mapping, for instance

.Map(m => m.MapKey("id_EntityName")

Upvotes: 1

DDiVita
DDiVita

Reputation: 4265

You can do this through setting up the mappings for your entities.

public class User
{
     public int Id {get;set;}
     public virtual Address Address {get;set;}


}

public class Address
{
     public int Id {get;set;}
     //Some other properties
}




public class UserMapping: EntityTypeConfiguration<User>
{
    public UserMapping()
    {
         HasOptional(u => u.Address).WithMany()
                                   .Map(m => m.MapKey("Id_Address"));

    }
}

//Override the OnModelCreating method in the DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
      modelBuild.Configurations.Add(new UserMapping());
}

Upvotes: 0

Related Questions