如何为EF5导航属性指定列名称

时间:2013-06-01 16:43:29

标签: entity-framework-5 ef-migrations

我首先使用EF5代码生成我的数据库模式,但我的新导航属性在表中以不受欢迎的方式命名。这是我正在使用的模型。

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

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

但是,在我更新了数据库并检查表列之后,该列的名称为:

dbo.ImagePermission.User_UserId

我希望它被命名为

dbo.ImagePermission.KeepThisNavigationName_UserId

我相信使用Fluent API有一种方法可以做到这一点,但经过多次尝试失败后,我无法获得理想的结果。

P.S。 'ImagePermission'实体目前仍处于开发阶段,因此我更愿意删除创建此表的迁移,以便在创建表时正确创建此列名,而不是使用其他代码来更新列名。

非常感谢,奥利弗

1 个答案:

答案 0 :(得分:4)

使用Fluent API的正确映射是:

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

如果ImagePermission中的导航属性引用User,则需要使用WithOptional(i => i.User)(或WithRequired(i => i.User))而不是无参数版本。

相关问题