Oliver Tomlinson
Oliver Tomlinson

Reputation: 595

How to specify a column Name for EF5 navigation property

I'm using EF5 code first to generate my database schema, but my new navigation property is being named in an undesirable way in the table. here is the model I'm working with.

public class User
{
    [Key]
    public long UserId { get; set; }
    ...

    **public virtual ICollection<ImagePermission> KeepThisNavigationName { get; set; }**
}

However, After I've updated my database and examine the table columns, the column is named:

dbo.ImagePermission.User_UserId

And I would like it to be named

dbo.ImagePermission.KeepThisNavigationName_UserId

I believe there is a way to do this using the Fluent API, but after many failed attempts, I can't get the desired outcome.

P.s. The 'ImagePermission' Entity is currently still in development, so I would prefer to drop the migration which creates this table so I can create this column name correctly during the table create, rather than having additional code to update the column name.

Many thanks, Oliver

Upvotes: 4

Views: 1274

Answers (1)

Slauma
Slauma

Reputation: 177163

The correct mapping with Fluent API would be:

modelBuilder.Entity<User>()
    .HasMany(u => u.KeepThisNavigationName)
    .WithOptional() // or WithRequired()
    .Map(m => m.MapKey("KeepThisNavigationName_UserId"));

If you have a navigation property in ImagePermission refering to User you need to use WithOptional(i => i.User) (or WithRequired(i => i.User)) instead of the parameterless version.

Upvotes: 4

Related Questions