【问题标题】:How to name foreign keys with database first approach如何使用数据库优先方法命名外键
【发布时间】:2014-07-25 14:49:33
【问题描述】:

有没有办法改变实体框架的命名约定?

例子:

我有两张桌子

Planification
--------------
creator_id <fk>
guest_id <fk>


Profile
--------------
profile_id <pk>

creator_idguest_id 都是 profile_id 的外键

默认情况下,实体会生成这样的平面类

public string guest_id { get; set; }
public string creator_id { get; set; }

public virtual Profile Profile { get; set; }
public virtual Profile Profile1 { get; set; }

我更喜欢比ProfileProfile1 更具体的东西,比如GuestCreator

有没有办法改变命名约定,因为这样让我感到非常内疚。

【问题讨论】:

    标签: c# entity-framework ef-database-first


    【解决方案1】:

    在您的 edmx 中,您可以通过单击属性并更改 Name 来重命名导航属性。

    请注意,如果您删除该表并再次从数据库构建它,您将不得不在 edmx 中重命名它。

    如果您对此感到非常恼火。绕过它的一种方法是使用带有属性的分部类,该属性为默认命名的属性提供名称。

    public partial class Planification
    {
        public Profile Creator 
        { 
            get{ return this.Profile1; }
            set{
                this.Profile1 = value;
            } 
        }
    
        public Profile Guest 
        { 
            get{ return this.Profile; }
            set{
                this.Profile = value;
            } 
        }
    }
    

    【讨论】:

    • 我就是这么想的,不容易啊。我将参加部分课程。这是一个绝妙的主意。谢谢!
    • 请注意,如果添加另一个外键并重新创建 edmx,“Profile1”可以更改上下文。
    • @Shoe 是的,但这让它非常危险。如果在某个时刻,不再需要外键并从表中删除。该外键下方的所有引用都将转移。根据您使用它们的方式,它可能会破坏您的整个应用程序,甚至不会给出编译错误。不过,您的方法会将代码更改保留在 1 个地方。
    • @MichaelD 我不同意它“非常危险”,但是如果您要更改密钥,可能会出现问题。在进行更改时,您应该尽自己的职责测试您的应用程序。我认为这个解决方案比重命名 edmx 中的属性更易于管理,这些属性在重新生成表时会被硬删除。如果您有更好的解决方案,我会全力以赴。
    • @Shoe '它可能发生' 如果您的业务逻辑突然使用另一个外键而您没有注意到没有任何构建错误或警告,则可能是灾难性的。只是因为在其他地方发生了一些变化。如果我有时间,我会编写一个更新 edmx xml 的后处理脚本。根据外部列名更改名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多