How to specify a column Name for EF5 navigation property

旧巷老猫 提交于 2019-12-07 11:02:24

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/16874887/how-to-specify-a-column-name-for-ef5-navigation-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!