How can we change naming convention of foreign keys in DB in EF Code First CTP5?
Asked Answered
L

1

9

I am using Entity framework Code First CTP5 and I am trying to find a way to add a convention to change how foreign keys name are generated. Here is an example:

public class Lead
{
    public int Id {get; set;}
    // A lot of other fields
    public virtual User AssignedTo { get; set; }
}

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

Lead can be associated to a user. The field generated in the DB for AssignedTo in the table Leads is called UserId.

My model is completely independent from entity framework. So I don't want to use attributes from EF. I would like to use the conventions if possible name the field AssignedToUserId for example.

Lice answered 24/2, 2011 at 21:34 Comment(0)
C
2

I'm not sure if this would be possible with pluggable conventions but you can use fluent API to achieve it:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Lead>()
                .HasRequired(l => l.AssignedTo)
                .WithMany()
                .IsIndependent()
                .Map(c => c.MapKey(u => u.Id, "AssignedToUserId"));
}
Cesta answered 25/2, 2011 at 1:14 Comment(1)
Yep this is what I am doing right now. But I don't want to have to do that everytime I add a new relation :).Lice

© 2022 - 2024 — McMap. All rights reserved.