如何为EF5导航属性指定列名 [英] How to specify a column Name for EF5 navigation property

查看:64
本文介绍了如何为EF5导航属性指定列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用EF5代码生成数据库架构,但是在表中以一种不希望的方式命名了我的新导航属性。这是我正在使用的模型。

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

我希望它被命名

dbo.ImagePermission.KeepThisNavigationName_UserId

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

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.

Ps ImagePermission实体当前仍在开发中,因此我宁愿删除创建该表的迁移,以便在创建表期间可以正确地创建此列名,而不用使用其他代码来更新该列名。

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.

非常感谢Oliver

Many thanks, Oliver

推荐答案

使用Fluent API的正确映射是:

The correct mapping with Fluent API would be:

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))而不是无参数版本。

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.

这篇关于如何为EF5导航属性指定列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆