Botond Balázs
Botond Balázs

Reputation: 2500

How to make Entity Framework use table names instead of class names when naming foreign keys?

If I have the following model:

[Table("Person")]
public class PersonDao
{
    public Guid Id { get; set; }
    public ICollection<Address> { get; set; }
    // other properties
}

[Table("Address")]
public class AddressDao
{
    public Guid Id { get; set; }
    public PersonDao Person { get; set; }
    // other properties
}

Entity Framework uses Person and Address correctly for the table names but the foreign key in Address is called PersonDao_Id. I want it to be Person_Id.

Is this a bug or am I supposed to write a custom convention for the property names?

NOTE: I use MySQL with Entity Framework, I don't know if that matters.

EDIT: I know that I can specify the column name manually using the ForeignKey attribute or the fluent API. I need this to work automatically and globally.

Upvotes: 1

Views: 2112

Answers (2)

CrazyBaran
CrazyBaran

Reputation: 592

If you want make your own name of column in database, you can use Fluent API in protected override void OnModelCreating(DbModelBuilder modelBuilder) method in your database context. Add to your DAO class properties with column name.

[Table("Person")]
public class PersonDao
{
    public Guid Id { get; set; }
    public ICollection<Address> Addresses { get; set; }
    // other properties
}

[Table("Address")]
public class AddressDao
{
    public Guid Id { get; set; }
    public Guid MyPersonDaoColumnName { get; set; }
    public PersonDao Person { get; set; }
    // other properties
}

and then in Fluent API write:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<AddressDao>().HasRequired(x => x.Person)
                                     .WithMany(x => x.Addresses)
                                     .HasForeignKey(x => x.MyPersonDaoColumnName);
}

but it is ugly to mix Fluent API with Attribute so you need also:

modelBuilder.Entity<AddressDao>.ToTable("Address");
modelBuilder.Entity<PersonDao>.ToTable("Person");

Upvotes: 0

D Stanley
D Stanley

Reputation: 152521

Use attributes just like you did to have different names for the table and class:

[Table("Address")]
public class AddressDao
{
    public Guid Id { get; set; }

    [ForeignKey("Person_Id")] 
    public PersonDao Person { get; set; }
    // other properties
}

If you don't want to use the default convention you could just remove Dao from your class names:

public class Person
{
    public Guid Id { get; set; }
    public ICollection<Address> { get; set; }
    // other properties
}

public class Address
{
    public Guid Id { get; set; }
    public Person Person { get; set; }
    // other properties
}

Upvotes: 2

Related Questions